<?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 Md Sajjad Hosen Noyon on Medium]]></title>
        <description><![CDATA[Stories by Md Sajjad Hosen Noyon on Medium]]></description>
        <link>https://medium.com/@noyoncse3101?source=rss-864e186c1d48------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*h7uytax2C4U2eA0IIiqppw.jpeg</url>
            <title>Stories by Md Sajjad Hosen Noyon on Medium</title>
            <link>https://medium.com/@noyoncse3101?source=rss-864e186c1d48------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 20:12:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@noyoncse3101/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[What happens when you enter a URL in Browsers?]]></title>
            <link>https://medium.com/@noyoncse3101/what-happens-when-you-enter-a-url-a1ea8873bef2?source=rss-864e186c1d48------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1ea8873bef2</guid>
            <category><![CDATA[html5]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[browsers]]></category>
            <category><![CDATA[web]]></category>
            <category><![CDATA[networking]]></category>
            <dc:creator><![CDATA[Md Sajjad Hosen Noyon]]></dc:creator>
            <pubDate>Wed, 08 Jan 2025 15:13:19 GMT</pubDate>
            <atom:updated>2025-01-19T08:27:52.093Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*I6ouVJ5zZqSMTd_m_X04ng.png" /></figure><p>Browsers are complex software applications that enable users to access, retrieve, and interact with information on the <strong>WWW</strong>. They are considered <strong>single-thread applications</strong>. It is the developers&#39; responsibility to improve browser performance so we have to understand in depth the different components of browsers and how they work.</p><p>Delivering a fast web experience is our daily life job. Browsers need to do a lot of work, and most of the work is hidden from us. But how do browsers consume HTML, CSS, and JavaScript to render pixels on screen? What happens when a URL is entered? We will discuss all of the stuff in this blog.</p><h3><strong>Browser Components</strong></h3><p>First, we have to understand the browser&#39;s components. The diagram below shows different parts of the browser components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*tnhpYlRb7Jk__s9XvAfOfQ.png" /><figcaption>Browsers components</figcaption></figure><p>A browser generally consists of:</p><ul><li><strong>User Interface (UI)</strong>: Buttons, address bar, tabs, etc.</li><li><strong>Browser Engine</strong>: Mediates between the UI and rendering engine.</li><li><strong>Rendering Engine</strong>: The renderer engines are written in C++, Rust, etc. Google Chrome Renderer Engine is written in C++. It converts HTML elements into node lists and renders web content (HTML, CSS) on the screen.</li><li><strong>JavaScript Engine</strong>: Executes JavaScript code.</li><li><strong>Networking Layer</strong>: Handles network requests.</li><li><strong>Data Storage</strong>: Manages cookies, local storage, session storage, and cache.</li></ul><h3>Browser’s visual Job for its User</h3><p>The browser’s primary job for users is to:</p><ol><li><strong>Display Data:</strong> Render the visual content for users.</li><li><strong>Enable Interactivity:</strong> Facilitate interactions with the rendered data.</li></ol><p>Below, we will discuss how browsers display a website and facilitate interaction with data.</p><h3><strong>Navigation</strong></h3><p>Navigation is the first step in loading a web page. It happens when a user enters a URL in the browser tab, and clicks a link/button or any other way. One of the main goals of web performance is to reduce the time for navigation to complete.</p><h3>DNS Lookup</h3><p>After the navigation, the browsers sent a request for DNS lookup which means to find an IP address against the domain name. After the initial response of the IP address, the browser caches it for further subsequent requests with the same domain.</p><p>Ever wondered what happens when someone enters a simple URL like <strong>google.com</strong> into the browser? When you hit Enter on your browser with such a URL, the following things happen:</p><ol><li><strong>Browser Cache:</strong> The browser first looks through its local cache to find the IP address for that domain. If it doesn’t find anything, it checks the service worker cache next.</li><li><strong>OS Search:</strong> If the address isn’t in those caches, the browser looks through the OS cache for any related data.</li><li><strong>ISP Cache:</strong> Still nothing? Now it’s time for ISP (Internet Service Provider), which keeps a cache of frequently requested domains to save time.</li><li><strong>DNS Lookup:</strong> If the IP address is still not found, the request reaches the DNS(Domain Name System), which works in four phases to resolve the domain.</li></ol><ul><li><strong>Root Level:</strong> Starting at the highest level, it checks the root servers.</li><li><strong>Top Level:</strong> The browser then checks for the TLD(.com, .net, .gov, etc)</li><li><strong>Second Level:</strong> Next, it looks up the domain itself(e.g, google of google.com)</li><li><strong>Third Level:</strong> Finally, the browser searches for subdomains like <a href="http://www.google.com/">www.google.com</a>.</li></ul><p>Once DNS finds the IP, it sends it to your ISP, which passes it back to the device. At this point, the browser sends a request for a handshake with the server(e.g., google.com), which is acknowledged by the server.</p><h3>TCP(Transmission Control Protocol) Connection</h3><p>After the DNS Lookup, browsers connect with a server through TCP handshaking. TCP handshaking is nothing but establishing a reliable connection between two devices over a network before data transmission. The TCP handshaking process involves three key steps:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/373/1*5_XM0Kt2ai2YQ_neFFB2sw.png" /><figcaption>3 ways handshaking</figcaption></figure><ol><li><strong>SYN(Synchronization):</strong> The client sends a SYN packet to the server to initiate a connection. This packet includes a unique sequential number.</li></ol><pre>Client → Server: SYN, Seq=1000</pre><p><strong>2. SYN-ACK(Synchronize-Acknowledgement): </strong>The server responds with a SYN-ACK packet to agree to the connection. The packet has the server’s own randomly generated sequence number. And an acknowledgement number which is the client’s sequence number incremented by 1.</p><pre>Server → Client: SYN, Seq=2000; ACK, Seq=1001</pre><p><strong>3. ACK(Acknowledgement):</strong> The client receives SYN-ACK packet and responds with an ACK packet having server sequence number incremented by 1.</p><pre>Client → Server: ACK, Seq=1001; ACK, Seq=2001</pre><p>At this point, the connection is fully established, and the client and server can begin exchanging data. Still, data exchange has not happened. After connecting via TCP, the browser wants to secure communication with the server. Then it asked about any SSL/TLS certificate within the server. If no SSL/TLS certificate is found, then the data is exchanged without encryption.</p><h3>What is SSL/TLS?</h3><p><strong>SSL (Secure Sockets Layer)</strong> and <strong>TLS (Transport Layer Security)</strong> are cryptographic protocols designed to provide secure communication over a network. TLS is the successor to SSL, with enhanced security and performance features. You can google for a better understanding or I’ll discuss it later in another blog.</p><h3><strong>How do HTML, and CSS download and construct Object Models?</strong></h3><p>Now we will see how the browser handles resources. When a browser loads a webpage, it follows a structured series of steps to fetch, parse, and render the content on the screen. Below is a detailed explanation of this process:</p><p><strong>1. Fetch phase</strong></p><p>Retrieves HTML, CSS and JS, and other resources from the server. The resources are loaded in a binary format(raw bytes) and passed to subsequent phases for processing.</p><p><strong>2. Parse Phase</strong></p><p><strong>HTML: </strong>The process of parsing an HTML file involves:</p><ul><li><strong>Loading Raw Bytes:</strong> The HTML file is received in binary format.</li><li><strong>Converting to Character:</strong> The binary data is decoded into a sequence of characters using the appropriate encoding.</li><li><strong>Tokenization:</strong> The characters are split into meaningful chunks called tokens(e.g.,&lt;div&gt;,&lt;p&gt;).</li><li><strong>Building structure:</strong> After tokenization, tokens are converted into objects/nodes, which form a tree-like structure. This structure includes relationships like parent, child, and samplings. Actually, converted into NodeList.</li><li><strong>Creating the DOM:</strong> The document Object Model is finally created. The DOM represents the structured layout of the webpage and contains objects of every element in the HTML.</li></ul><p><strong>CSS: </strong>The process of parsing CSS files is similar to HTML. But it builds CSSOM instead of DOM. DOM and CSSOM are completely independent. Parallelly CSSOM was created besides DOM. They are eventually combined to form the rendering tree. This tree is then used to determine the visual layout of the page.</p><p><strong>3. Rendered Tree</strong></p><p>It gathers the information of <strong>DOM</strong> and <strong>CSSOM</strong> and gives it to the <strong>Browser Engine</strong>. Browser is a master in math and a lot of mathematical calculation is done. This merged tree is passed to the Browser Engine which performs a complex mathematical calculator to determine how elements should appear on the screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*djUgsAqMNygdEvWhWOlpUA.png" /></figure><p><strong>4. Layout</strong></p><p>Calculate the exact position and size of every element on the page in the Render Tree. The process involves applying various layout algorithms like the box model, flexbox, and grid layout. Then we got a rendering tree. And at that moment the painting started.</p><p><strong>5. Painting</strong></p><p>The browser paints the element onto the screen, pixel by pixel.</p><h3>How does JavaScript download and execute?</h3><p>When the browser encounters a <strong>&lt;script&gt;</strong> tag in the HTML, it pauses further <strong>HTML parsing</strong> to download, parse, and execute the JavaScript unless <strong>async</strong> or <strong>defer</strong> is used.</p><p><strong>Blocking behavior of JavaScript</strong></p><p>By default, &lt;script&gt; tags block HTML parsing. Without <strong>async</strong> or <strong>defer</strong>, the browser:</p><ul><li>Stops parsing HTML.</li><li>Downloads and executes the script.</li><li>Resumes parsing the HTML.</li></ul><p>This blocking behavior can delay the page load, especially if the script is large or hosted on a slow server.</p><p><strong>Async Attribute</strong></p><p>The script is downloaded <strong>asynchronously</strong> while the HTML is being parsed. Scripts are executed as soon as they’re ready and the execution order is unpredictable(depends on which script loads first).</p><pre>&lt;script src=&quot;script.js&quot; async&gt;&lt;/script&gt;</pre><p><strong>Defer attribute</strong></p><p>The script is downloaded asynchronously while the HTML is being parsed. The script is executed after the HTML parsing is completed,<strong> in the order they appear</strong>. Ensures the DOM is fully constructed before the script runs.</p><pre>&lt;script src=&quot;script.js&quot; defer&gt;&lt;/script&gt;</pre><p><strong>Comparison between sync, defer, and None</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*UCDJvhX1EfX1k1wJvk9jzg.png" /></figure><p><strong>Best practices</strong></p><ul><li>Use <strong>defer</strong> for scripts that depend on the DOM (e.g., UI scripts).</li><li>Use <strong>async</strong> for independent scripts (e.g., analytics).</li><li>Place blocking scripts at the end of the <strong>&lt;body&gt;</strong> tag if <strong>async</strong> or <strong>defer</strong> are not used.</li><li>Minimize JavaScript and use bundling techniques for better performance.</li></ul><h3>Resources</h3><ol><li><a href="https://web.dev/articles/critical-rendering-path">https://web.dev/articles/critical-rendering-path</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/Performance/How_browsers_work">https://developer.mozilla.org/en-US/docs/Web/Performance/How_browsers_work</a></li></ol><p><strong><em>Thanks for reading.</em></strong><em> If you have any thoughts or suggestions, feel free to reach me.</em></p><p><em>You can follow me on </em><a href="https://x.com/noyon310197">Twitter</a>, <a href="https://github.com/NYN31">GitHub</a>, and <a href="https://www.linkedin.com/in/noyon31/">LinkedIn</a>.</p><p><strong><em>See you! 👋</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1ea8873bef2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java HashMap Internal]]></title>
            <link>https://medium.com/@noyoncse3101/java-hashmap-internal-ad4e238f7dab?source=rss-864e186c1d48------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad4e238f7dab</guid>
            <category><![CDATA[internal]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[hashmap]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Md Sajjad Hosen Noyon]]></dc:creator>
            <pubDate>Thu, 31 Oct 2024 13:10:10 GMT</pubDate>
            <atom:updated>2024-12-02T11:04:19.767Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*jSfBEV2R0WTqyh5R-YyzPw.png" /></figure><p>Map is a part of the Java Collection Framework. However, it differs slightly from other collections in the framework because it does not implement the Collection interface directly. Instead, Map is a standalone interface designed for key-value pairs, and it operates differently from the other Collection types(List, Set, Queue) that store individual elements.</p><p>In Java, HashMap is a widely used implementation of Map interface within the Java Collection Framework which is by default not synchronized(not thread-safe). It is a <strong>hash table-based</strong> implementation of the Map interface. A hash table uses a hash function to compute an index, also called a hash code, into an array of buckets or slots, from which the desired value can be found. During lookup, the supplied key is hashed, and the resulting hash indicates where the corresponding value is stored. In this article, we will explore the internals of HashMap.</p><h4>Internal Structure of a HashMap</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*AtEgDqXCEimJ7FbRnuJiNg.png" /></figure><p>Internally, a HashMap uses an array of buckets or bins. Each bucket is a linked list of type Node, which represents the key-value pair of the HashMap. The Node type is given below:</p><pre>static class Node&lt;K,V&gt; implements Map.Entry&lt;K,V&gt; {<br>        final int hash;<br>        final K key;<br>        V value;<br>        Node&lt;K,V&gt; next;<br><br>        Node(int hash, K key, V value, Node&lt;K,V&gt; next) {<br>            this.hash = hash;<br>            this.key = key;<br>            this.value = value;<br>            this.next = next;<br>        }<br>}</pre><p>The Node class has the following fields:</p><ul><li>hash: Refers to the hashCode of the key.</li><li>key: Refers to the key of the key-value pair.</li><li>value: Refers to the value associated with the key.</li><li>next: This attribute acts as a reference to the next node. It holds the pointer to the next key-value pair and stores the key-value pairs as a linked list.</li></ul><p>Hashmap initially takes a fixed no of buckets or bins of key-value pairs of linked list. When key-value pairs in HashMap exceed a certain threshold, determined by the load factor, all key-value pairs would be resized and rehashed. This process is called rehashing or resizing.</p><p>The purpose of resizing is to prevent excessive collisions reducing load factor below a certain threshold, which can lead to degraded performance. By increasing the capacity(number of buckets) of the hashmap and redistributing the key-value pairs, the load factor is reduced, and the HashMap can maintain its efficiency.</p><h3>Few Constant Variables in Map Interface</h3><p>Before going into further about the implementation classes, it will be helpful to understand the following terminologies:</p><ol><li><strong>Initial and Max capacity: </strong>The default initial capacity is 16 which is an initial number of buckets in HashMap. It must be a power of 2. And The maximum capacity it 2³⁰(1 billion entries).</li></ol><pre>DEFAULT_INITIAL_CAPACITY = 1 &lt;&lt; 4; // 16<br>static final int MAXIMUM_CAPACITY = 1 &lt;&lt; 30;</pre><p><strong>2. Load Factor: </strong>As you keep adding elements, the key value of pairs increases in buckets. When the number of elements exceeds a certain threshold, determined by the load factor, the HashMap resizes its internal storage to maintain efficiency. The default load factor is 0.75, which means after a full 75% memory, HashMap will resize with a capacity double. For example, if the current size of HashMap is 16 then the resizing will happen when (16 * 75%) = 12 buckets are full.</p><pre>static final float DEFAULT_LOAD_FACTOR = 0.75f;</pre><p><strong>3. Treeify Threshold: </strong>When a bucket(an individual bin in the array backing the hashmap) has 8 or more nodes, it switches from a linked list to a tree structure to reduce lookup time from O(n) to O(log n). This threshold improves performance in cases with many collisions.</p><pre>static final int TREEIFY_THRESHOLD = 8;</pre><p><strong>4. Untreefiy threshold:</strong> During a resize operation, if a bin’s number of nodes falls below 6, it converts the tree back into a linked list. This threshold prevents the structure from maintaining unnecessary tree structures when they’re no longer needed.</p><pre>static final int UNTREEIFY_THRESHOLD = 6;</pre><p><strong>5. Minimum treefiy capacity: </strong>The minimum capacity of buckets in HashMap must be at least 64 for treeify to occur.<strong> If there are too many entries in HashMap but less than 64 buckets, it resizes the entire hashmap rather than converting a bin to a tree from a linked list.</strong> This strategy keeps resizing separate from Treeify, improving performance consistency. Below field determines when to treeify of bin or resize of HashMap size.</p><pre>static final int MIN_TREEIFY_CAPACITY = 64;</pre><h4>Linked list to Balanced trees</h4><p>Starting with Java 8, if the number of entries in a single bucket of HashMap exceeds a certain threshold (TREEIFY_THRESHOLD, set to 8 by default), the structure of that bucket changes from a linked list to a Red-Black Tree. This optimization helps to speed up search operations in that bucket from O(n) with a linked list to O(log⁡n) using the tree.</p><p>During rehashing, this transformation occurs for any bucket with more than 8 entries, ensuring more efficient retrieval as the map grows. However, when the number of entries in a tree bucket drops below a different threshold (UNTREEIFY_THRESHOLD, set to 6), it reverts back to a linked list. This conversion back to a linked list saves memory, as TreeNodes consume more space than basic Map.Entry nodes. By balancing between linked lists and trees based on the number of entries, HashMap achieves both memory efficiency and performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*5tZ5_V3l0atE3rBGmN2PWA.png" /></figure><p><strong>NOTES:</strong> In the above image, the tree is not like a balance tree, but imagine it&#39;s a Balance tree.</p><p><strong>There are several balance trees such as AVL trees, Red-black trees, Splay trees, etc. Then what is The Red-Black tree? The red-Black</strong> tree is a self-balancing binary search tree. The red-black tree makes sure that the length/depth of the binary search trees is always log(n) in spite of new additions or removal of nodes.</p><p><strong>The primary benefit of using a Red-Black tree in cases where multiple entries fall into the same bucket is that it optimizes search operations. In Java 7, if entries are stored in a linked list, searching through them takes O(n) time complexity. However, Java 8 introduced a Red-Black tree structure for these cases, reducing search time to O(log⁡(n)) by organizing the entries as a balanced tree instead of a linear list.</strong></p><p><strong>Drawbacks</strong>: The tree takes more space than the linked list. By Inheritance, a bucket can contain both Node(Entry object) and TreeNode(Red-black tree).</p><h4>Time Complexity</h4><p>The basic operations of a HashMap, such as put, get, and remove, generally offer constant time performance of O(1), assuming that the keys are uniformly distributed. In cases where there is poor key distribution and many collisions occur, these operations might degrade to a linear time complexity of O(n).</p><p>Under treeification, where long chains of collisions are converted into balanced trees, lookup operations can improve to a more efficient logarithmic time complexity of O(log n).</p><p><strong><em>Thanks for reading.</em></strong><em> If you have any thoughts or suggestions, feel free to reach me.</em></p><p><em>You can follow me on </em><a href="https://x.com/noyon310197">Twitter</a>, <a href="https://github.com/NYN31">GitHub</a>, and <a href="https://www.linkedin.com/in/noyon31/">LinkedIn</a>.</p><p><strong><em>See you! 👋</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad4e238f7dab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Pattern 03 - Observer]]></title>
            <link>https://medium.com/@noyoncse3101/design-pattern-03-observer-design-758ac25f2db7?source=rss-864e186c1d48------2</link>
            <guid isPermaLink="false">https://medium.com/p/758ac25f2db7</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Md Sajjad Hosen Noyon]]></dc:creator>
            <pubDate>Mon, 21 Oct 2024 08:31:32 GMT</pubDate>
            <atom:updated>2024-10-24T05:04:31.163Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*DJBFs3LoMBVYCx5xw6MITQ.png" /></figure><p>The Observer Design Pattern is a powerful pattern in object-oriented programming. It is a behavioral design pattern used to create one-to-many relations between objects so that when one object(subject) changes its state, all its dependents (observer) are notified and updated automatically. This pattern is widely used in scenarios where an object needs to broadcast changes to multiple dependent objects without them being tightly coupled. In this blog, we will grasp what is Observer design pattern, explore its components, and how it works.</p><h4>Characteristic of Observer design pattern</h4><ol><li><strong>Decoupling</strong>: The subject (the entity being observed) does not need to know who its observers are or what they do. It only broadcasts its state changes, and the observers handle these updates accordingly. This loose coupling makes the system more flexible and scalable.</li><li><strong>One-to-Many Relationship</strong>: The pattern facilitates a <strong>one-to-many</strong> relationship between a subject and its observers. When the state of the subject changes, all attached observers are notified and can react in their way.</li><li><strong>Subject and Observer Interface</strong>: The <strong>Subject</strong> typically provides methods to add, remove, and notify observers. Observers implement a common interface that requires them to have an update() method, which gets called when the subject&#39;s state changes.</li><li><strong>Automatic State Updates</strong>: When a subject’s state changes, it automatically notifies all its registered observers, typically through a method like notifyObservers(). The observers then pull the new state of the subject.</li><li><strong>Dynamic and Reusable</strong>: Observers can be added or removed at runtime, allowing dynamic changes to how the system behaves. This makes the pattern highly reusable across different contexts.</li><li><strong>Chain of Events</strong>: Changes in one object can lead to changes in others, triggering a cascade of notifications. This can create a reactive system where objects react automatically to changes in other objects.</li></ol><h4>Components of the Observer Design Pattern</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/0*HAysQlykvRJiz19U.png" /></figure><ol><li><strong>Subject:</strong> The subject maintains a list of observers and notifies them of state changes.</li><li><strong>Observer:</strong> The observer interface defines the contract for concrete observer classes.</li><li><strong>ConcreteSubject:</strong> A class that implements the subject interface and manages the observers.</li><li><strong>ConcreteObserver:</strong> A class that implements the observer interface and receives notifications.</li></ol><h4>Implementing Observer Design Pattern: Smart Home Automation System</h4><p>In the below example, the <strong>subject</strong> is a <strong>HomeController</strong>, which monitors various home conditions like motion detection, temperature, or security breaches. Different <strong>devices</strong> such as lights, cameras, alarms, or thermostats act as <strong>observers</strong> that react to the updates in the home system.</p><h4>Scenario:</h4><ul><li>A <strong>motion sensor</strong> detects movement in the living room.</li><li>If any movement is detected the <strong>smart light</strong> turns on, and the <strong>security camera</strong> starts recording.</li></ul><p><strong>Step 1:</strong> <strong>Observer Interface</strong></p><pre>// Observer Interface<br>interface SmartDevice {<br>    void update(String condition);<br>}</pre><p><strong>Step 2:</strong> <strong>Create the ConcreteObserver class</strong></p><pre>// Concrete Observer (Light)<br>class SmartLight implements SmartDevice {<br>    @Override<br>    public void update(String condition) {<br>        if (condition.equals(&quot;Motion Detected&quot;)) {<br>            System.out.println(&quot;Smart Light: Motion detected, turning on lights.&quot;);<br>        } else {<br>            System.out.println(&quot;Smart Light: No motion, lights off.&quot;);<br>        }<br>    }<br>}<br><br>// Concrete Observer (Security Camera)<br>class SecurityCamera implements SmartDevice {<br>    @Override<br>    public void update(String condition) {<br>        if (condition.equals(&quot;Motion Detected&quot;)) {<br>            System.out.println(&quot;Security Camera: Motion detected, starting recording.&quot;);<br>        } else {<br>            System.out.println(&quot;Security Camera: No motion, recording stopped.&quot;);<br>        }<br>    }<br>}</pre><p><strong>Step 3: Subject Interface</strong></p><pre>// Subject Interface<br>interface HomeController {<br>    void addDevice(SmartDevice device);<br>    void removeDevice(SmartDevice device);<br>    void notifyDevices();<br>}</pre><p><strong>Step 4: ConcreteSubject class</strong></p><pre>// Concrete Subject (Home Controller)<br>class HomeControlSystem implements HomeController {<br>    private List&lt;SmartDevice&gt; devices;<br>    private String homeCondition;<br><br>    public HomeControlSystem() {<br>        devices = new ArrayList&lt;&gt;();<br>    }<br><br>    public void setHomeCondition(String condition) {<br>        this.homeCondition = condition;<br>        notifyDevices();<br>    }<br><br>    @Override<br>    public void addDevice(SmartDevice device) {<br>        devices.add(device);<br>    }<br><br>    @Override<br>    public void removeDevice(SmartDevice device) {<br>        devices.remove(device);<br>    }<br><br>    @Override<br>    public void notifyDevices() {<br>        for (SmartDevice device : devices) {<br>            device.update(homeCondition);<br>        }<br>    }<br>}</pre><p>Step 5: Make it Happen</p><pre>// Test Client Code<br>public class SmartHomeTest {<br>    public static void main(String[] args) {<br>        HomeControlSystem homeController = new HomeControlSystem();<br><br>        SmartLight livingRoomLight = new SmartLight();<br>        SecurityCamera livingRoomCamera = new SecurityCamera();<br><br>        homeController.addDevice(livingRoomLight);<br>        homeController.addDevice(livingRoomCamera);<br><br>        // Simulate a home condition change: Motion detected<br>        homeController.setHomeCondition(&quot;Motion Detected&quot;); // Both devices react<br><br>        // Simulate no motion<br>        homeController.setHomeCondition(&quot;No Motion&quot;); // Both devices react<br>    }<br>}</pre><h4>Explanation:</h4><ul><li><strong>HomeControlSystem</strong>: This is the subject that maintains the current condition of the home (e.g., “Motion Detected” or “No Motion”). It notifies all registered devices whenever the condition changes.</li><li><strong>SmartLight and SecurityCamera</strong>: These are the concrete observers that react to changes in the home condition. When motion is detected, the light turns on, and the camera starts recording.</li><li><strong>notifyDevices()</strong>: Whenever the home condition changes, this method is triggered, and all devices (observers) update accordingly.</li></ul><h4>Value of the Observer Design Pattern:</h4><ul><li><strong>Real-time Automation</strong>: Whenever motion is detected, multiple devices are triggered, ensuring the system responds automatically to events without tight coupling.</li><li><strong>Scalability</strong>: More devices can be added to the system (e.g., smart locks, and alarms) without changing the core logic of the home controller.</li><li><strong>Flexibility</strong>: Each device can independently decide how to react to home conditions, making the system extensible and dynamic.</li></ul><p>This scenario showcases how The <strong>Observer Pattern</strong> can be used in IoT (Internet of Things) or smart home applications, where multiple devices respond to events like motion, temperature changes, or security breaches.</p><p><strong><em>Thanks for reading.</em></strong><em> If you have any thoughts or suggestions, feel free to comment below.</em></p><p><em>You can follow me on </em><a href="https://x.com/noyon310197">Twitter</a>, <a href="https://github.com/NYN31">GitHub</a>, and <a href="https://www.linkedin.com/in/noyon31/">LinkedIn</a>.</p><p><strong><em>See you! 👋</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=758ac25f2db7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Pattern 02 - Strategy]]></title>
            <link>https://medium.com/@noyoncse3101/design-pattern-02-strategy-design-c8883bc1d675?source=rss-864e186c1d48------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8883bc1d675</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Md Sajjad Hosen Noyon]]></dc:creator>
            <pubDate>Mon, 23 Sep 2024 04:58:06 GMT</pubDate>
            <atom:updated>2025-01-19T05:29:01.221Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*gvUVJz9-o1Oe2Ova-0_JEA.png" /></figure><p>The Strategy Design Pattern is a powerful pattern in the world of object-oriented programming. It provides a flexible way to encapsulate, choose from multiple algorithms, and swap the behavior of an object at runtime, enabling code to be more adaptable and easier to maintain. The core idea behind this <strong>behavioral pattern</strong> is to separate the algorithms from the main object. This allows the object to delegate the algorithm’s behavior to one of its contained strategies.</p><h4>Characteristics of the Strategy Design Pattern?</h4><p>The Strategy Design Pattern exhibits several key characteristics that make it distinctive and effective for managing algorithm variations in software systems:</p><ul><li><strong>It defines a family of algorithms:</strong> The pattern allows you to encapsulate multiple algorithms or behaviors into separate classes, known as strategies.</li><li><strong>It encapsulates behaviors:</strong> Each strategy encapsulates a specific behavior or algorithm, providing a clean and modular way to manage different variations or implementations.</li><li><strong>It enables dynamic behavior switching:</strong> The pattern enables a client to switch between different strategies at runtime, allowing for flexible and dynamic behavior changes.</li><li><strong>It promotes object collaboration:</strong> The pattern encourages collaboration between a context object and strategy objects, where the context delegates the execution of a behavior to a strategy object.</li></ul><p>Overall, the Strategy pattern is a useful design pattern that allows the behavior of an object to be selected dynamically at runtime, providing flexibility, modularity, and testability.</p><h4>Components of the Strategy Design Pattern</h4><p>The Strategy Design Pattern consists of four primary components:</p><p><strong>Context:</strong> The object that will delegate its behavior. The context maintains a reference to a strategy object and interacts with it through an interface.</p><p><strong>Strategy Interface:</strong> The interface that defines the behavior for all strategies. The strategies implement this interface to provide their unique implementation.</p><p><strong>Strategies:</strong> The classes that implement the Strategy interface. Each strategy encapsulates a specific behavior that the context can switch at runtime.</p><p><strong>Client:</strong> The Client is responsible for creating, selecting, and configuring the appropriate strategy and providing it to the Context.</p><h4>Code Example</h4><p>Let’s consider the following code example:</p><pre>public class PaymentProcessor {<br>    private PaymentType paymentType;<br><br>    public void processPayment(double amount) {<br>        if (paymentType == PaymentType.CREDIT_CARD) {<br>            System.out.println(&quot;Processing credit card payment of amount &quot; + amount);<br>        } else if (paymentType == PaymentType.DEBIT_CARD) {<br>            System.out.println(&quot;Processing debit card payment of amount &quot; + amount);<br>        } else if (paymentType == PaymentType.PAYPAL) {<br>            System.out.println(&quot;Processing PayPal payment of amount &quot; + amount);<br>        } else {<br>            throw new IllegalArgumentException(&quot;Invalid payment type&quot;);<br>        }<br>    }<br><br>    public void setPaymentType(PaymentType paymentType) {<br>        this.paymentType = paymentType;<br>    }<br>}<br><br>enum PaymentType {<br>    CREDIT_CARD,<br>    DEBIT_CARD,<br>    PAYPAL<br>}</pre><p>In this code, the PaymentProcessor class has a processPayment method that takes a parameter payment amount and processes the payment. The setPaymentType method sets the payment type. The processPayment method then checks the process type and processes the payment accordingly.</p><p>The problem with this approach is that it violates the Open-Closed principle. In this code, if you want to add a new payment method, you have to modify the processPayment method, and it also determines the process payment type through conditional statements, which violates the Open-Closed principle.</p><p>To fix this problem, we can use the Strategy Design Pattern. First, define a common interface for all payment strategies, which in this case is the PaymentStrategy interface:</p><pre>public interface PaymentStrategy {<br>    void processPayment(double amount);<br>}</pre><p>Then define the implementation of the PaymentStrategy interface for each payment strategy.</p><pre>public class CreditCardPaymentStrategy implements PaymentStrategy {<br>    public void processPayment(double amount) {<br>        System.out.println(&quot;Processing credit card payment of amount &quot; + amount);<br>    }<br>}<br><br>public class DebitCardPaymentStrategy implements PaymentStrategy {<br>    public void processPayment(double amount) {<br>        System.out.println(&quot;Processing debit card payment of amount &quot; + amount);<br>    }<br>}<br><br>public class PaypalPaymentStrategy implements PaymentStrategy {<br>    public void processPayment(double amount) {<br>        System.out.println(&quot;Processing PayPal payment of amount &quot; + amount);<br>    }<br>}</pre><p>Finally, update the PaymentProcessor class (Context) to take a PaymentStrategy object in its constructor, which is used to process the payment:</p><pre>public class PaymentProcessor {<br>    private PaymentStrategy paymentStrategy;<br><br>    public PaymentProcessor(PaymentStrategy paymentStrategy) {<br>        this.paymentStrategy = paymentStrategy;<br>    }<br><br>    public void processPayment(double amount) {<br>        paymentStrategy.processPayment(amount);<br>    }<br>}</pre><p>This implementation follows the Open-Closed Principle as well as the Strategy Pattern because you can add new payment types by creating new implementations of the PaymentStrategy interface without modifying the existing code.</p><h4>References</h4><ol><li><a href="https://www.geeksforgeeks.org/strategy-pattern-set-1/">https://www.geeksforgeeks.org/strategy-pattern-set-1/</a></li><li><a href="https://refactoring.guru/design-patterns/strategy">https://refactoring.guru/design-patterns/strategy</a></li></ol><h4>Conclusion</h4><p>This blog has covered characteristics, components, and implementation of Strategy Design Patterns. If you want to learn more, have a look at the reference section.</p><p><strong><em>Thanks for reading.</em></strong><em> If you have any thoughts or suggestions, feel free to comment below.</em></p><p><em>You can follow me on </em><a href="https://x.com/noyon310197">Twitter</a>, <a href="https://github.com/NYN31">GitHub</a>, and <a href="https://www.linkedin.com/in/noyon31/">LinkedIn</a>.</p><p><strong><em>See you! 👋</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8883bc1d675" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Shallow Copy vs Deep Copy of Object— JavaScript]]></title>
            <link>https://medium.com/@noyoncse3101/shallow-copy-vs-deep-copy-of-object-javascript-b525d0767276?source=rss-864e186c1d48------2</link>
            <guid isPermaLink="false">https://medium.com/p/b525d0767276</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[shallow-vs-deep-copy]]></category>
            <dc:creator><![CDATA[Md Sajjad Hosen Noyon]]></dc:creator>
            <pubDate>Wed, 14 Aug 2024 05:32:58 GMT</pubDate>
            <atom:updated>2025-08-12T12:20:33.121Z</atom:updated>
            <content:encoded><![CDATA[<p>In JavaScript, there are two ways to copy objects. The first is a Shallow copy and the second is a Deep copy. Understanding the difference between both is important for those who work with JavaScript.</p><h4>Shallow Copy</h4><p><strong>A shallow copy </strong>means only the first level of the object is copied. <strong>Deeper levels are referenced.</strong></p><p>There is one big caveat when dealing with coping objects. When you have a nested object(or array) and you copy it, nested objects inside that object will not be copied, since they are only references. Therefore, if you change the nested object, you will change it for both instances, meaning you will end up doing a shallow copy.</p><p>There are two ways of a shallow copy. Using Spreed(…) operators or Object.assign() method.</p><pre>const originalObj = { name: &#39;noyon&#39;, additionalInfo: { version: 1 }};<br><br>const shallowCopy1 = { ...originalObj };<br>const shallowCopy2  = Object.assign({}, originalObj);<br><br>shallowCopy1.name = &#39;hossain&#39;;<br>shallowCopy1.additionalInfo.version = 2;<br><br>console.log(originalObj); // { name: &#39;noyon&#39;, additionalInfo: { version: 2 }}<br>console.log(shallowCopy1); // { name: &#39;hossain&#39;, additionalInfo: { version: 2 }}<br><br>shallowCopy2.name = &#39;mosharraf&#39;;<br>shallowCopy2.additionalInfo.version = 3;<br><br>console.log(originalObj); // { name: &#39;noyon&#39;, additionalInfo: { version: 3 }}<br>console.log(shallowCopy1); // { name: &#39;mosharraf&#39;, additionalInfo: { version: 3 }}<br>console.log(shallowCopy2); // { name: &#39;mosharraf&#39;, additionalInfo: { version: 3 }}</pre><p>As you can see in this code snippet:</p><ol><li>After updating a property in the first level of the clone object, the original property is not updated.</li><li>After updating a property on a deeper level, the original property is also updated. This happens because, in this case, deeper levels are referenced, not copied.</li></ol><h4>Deep copy</h4><p>A deep copy means that all levels of the object are copied. This is a true copy of an object.</p><p>It creates a new object with new memory locations for all of its properties and nested objects. This means that if you make changes to the copied object or any of its nested objects, it will not affect the original object.</p><p>To make a deep copy of nested objects, you need to copy manually every nested object.</p><pre>const originalObj = {<br>  a: 1,<br>  b: {<br>    c: 3,<br>    d: {<br>      e: 5,<br>      f: 6,<br>    }<br>  },<br>};<br><br>const deepCopy = {<br>  ...originalObj,<br>  b: {<br>    ...originalObj.b,<br>    c: &#39;c-updated&#39;,<br>    d: { ...originalObj.b.d, e: &#39;e-updated&#39; },<br>  },<br>};<br><br>console.log(originalObj);<br>/*** {<br>  a: 1,<br>  b: {<br>    c: 3,<br>    d: {<br>      e: 5,<br>      f: 6<br>    }<br>  }<br>} ***/<br>console.log(deepCopy);<br>/*** {<br>  a: 1,<br>  b: {<br>    c: &#39;c-updated&#39;,<br>    d: {<br>      e: &#39;e-updated&#39;,<br>      f: 6<br>    }<br>  }<br>} ***/<br></pre><p>As you can see in the above code snippet, you have to copy every nested object using the spread(…) operator. This is a very tedious and buggy approach to copying a full object. There are other ways to make a deep copy without thinking.</p><pre>const originalObj = { name: &#39;noyon&#39;, additionalInfo: { version: 1 }};<br><br>// const deepClone = structuredClone(user); // modern and safe<br>const deepCopy = JSON.parse(JSON.stringify(originalObj)); // older trick, but loses functions, undefined, etc.<br><br>deepCopy.name = &#39;hossain&#39;;<br>deepCopy.additionalInfo.version = 2;<br><br>console.log(originalObj); // { name: &#39;noyon&#39;, additionalInfo: { version: 1}}<br>console.log(deepCopy); // { name: &#39;hossain&#39;, additionalInfo: { version: 2 }}<br><br></pre><p>As you can see in the above code snippet:</p><ol><li>After updating a property in the first level of the cloned object, the original property is not updated.</li><li>After updating a property on a deeper level, the original property is not updated. This happens because, in this case, deeper levels are also copied.</li></ol><p>Alright, you can see <strong>structuredClone()</strong> in the above code. It’s a built-in global function in modern JavaScript that creates a <strong>deep clone</strong> of almost any JavaScript value, including plain objects, arrays, Maps, Sets, typed arrays and ArrayBuffers, Dates &amp; RegExps(data only).</p><pre>const user = {<br>  name: &quot;Noyon&quot;,<br>  skills: { lang: &quot;JavaScript&quot; },<br>  dates: [new Date(), new Date(&quot;2025-01-01&quot;)]<br>};<br><br>const copy = structuredClone(user);<br><br>copy.name = &quot;Hossain&quot;;<br>copy.skills.lang = &quot;Python&quot;;<br><br>console.log(user.name); // &quot;Noyon&quot; ✅ (not affected)<br>console.log(user.skills.lang); // &quot;JavaScript&quot; ✅ (deep copy worked)</pre><h4>Limitatation of structuredClone()</h4><ol><li>Functions cannot be cloned.</li><li>Symbol properties are not cloned.</li><li>DOM nodes (like document.body) cannot be cloned.</li><li>Certain host objects (e.g., WebSockets, HTML elements) are not supported.</li></ol><h4>Why Choose structuredClone()?</h4><p>What does JSON.parse(JSON.stringify(obj)) do?</p><ul><li>Converts the object into a JSON string.</li><li>Parses it back into a new JavaScript Object.</li><li>Loses any data that can’t be represented in JSON.</li></ul><p><strong>Example of data loss:</strong></p><pre>const obj = {<br>  date: new Date(),<br>  undef: undefined,<br>  func: () =&gt; console.log(&quot;hi&quot;),<br>  symbol: Symbol(&#39;id&#39;),<br>};<br><br>const clone = JSON.parse(JSON.stringify(obj));<br><br>console.log(clone);<br>// {<br>//   date: &quot;2025-08-12T14:00:00.000Z&quot;, // becomes string<br>//   // `undef` removed<br>//   // `func` removed<br>//   // `symbol` removed<br>// }</pre><p><strong>Problems:</strong></p><ul><li>Dates become strings.</li><li>undefined is removed.</li><li>Functions are removed.</li><li>Symbols are removed.</li><li>Prototypes are lost.</li></ul><h4><strong>What does structuredClone() do?</strong></h4><ul><li>Preserves <strong>dates, maps, sets, typed arrays, and nested objects</strong> correctly.</li><li>Supports circular references.</li><li>Does <strong>not</strong> convert data to strings unless needed.</li><li>Has a wider range of supported types.</li></ul><pre>const obj = {<br>  date: new Date(),<br>  map: new Map([[&quot;a&quot;, 1]]),<br>  set: new Set([1, 2, 3]),<br>  nested: { a: 1 },<br>  circular: null<br>};<br><br>obj.circular = obj; // circular reference<br><br>const clone = structuredClone(obj);<br><br>console.log(clone.date instanceof Date); // true<br>console.log(clone.map instanceof Map);   // true<br>console.log(clone.set instanceof Set);   // true<br>console.log(clone.circular === clone);   // true</pre><h4>Conclusion along with performance</h4><p>A deep copy can be more expensive in terms of performance than a shallow copy for the above reasons. So, a shallow copy is faster than a deep copy. But this doesn’t mean that you should always use a shallow copy, because sometimes you will also need a copy of the nested objects, whereas a deep copy is important.</p><p><strong><em>Thanks for reading.</em></strong><em> If you have any thoughts or suggestions, feel free to comment below.</em></p><p><em>You can follow me on </em><a href="https://x.com/noyon310197">Twitter</a>, <a href="https://github.com/NYN31">GitHub</a>, and <a href="https://www.linkedin.com/in/noyon31/">LinkedIn</a>.</p><p><strong><em>See you! 👋</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b525d0767276" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Design Pattern Part 4: State Reducer]]></title>
            <link>https://medium.com/@noyoncse3101/react-design-pattern-part-4-state-reducer-64cc375f220e?source=rss-864e186c1d48------2</link>
            <guid isPermaLink="false">https://medium.com/p/64cc375f220e</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Md Sajjad Hosen Noyon]]></dc:creator>
            <pubDate>Sun, 07 Jul 2024 11:07:08 GMT</pubDate>
            <atom:updated>2024-08-14T05:28:23.414Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f8RKxRU73h9oF6utF4UuDQ.png" /></figure><p>For the state reducer pattern, we have to use a powerful hook useReducer. This hook is the better alternative to useState hook. When your component or application state management becomes complex, the reducer state pattern is a savior. useReducer hook helps to manage complex state management logic in React applications. Also, combining useContext and useReducer hook can be a good alternative to <strong>Redux</strong>, <strong>Recoil</strong>, or <strong>MobX</strong>. In certain cases, it is an outright better option. We can use this pattern for global state management.</p><h4># When to use</h4><ul><li>It is used when more advanced state management is needed, especially in applications with complex state logic.</li><li>Using it has the benefit of predictability and traceability of state updates.</li><li>When you want to centralize state update logic in one place.</li></ul><h4># When not to use</h4><p>Despite being able to use the useReducer hook to handle complex state logic in our app, it’s important to note that there are some scenarios where a third-party state management library like <strong>Redux</strong> may be a better option.</p><ul><li>In small or simple applications state management is simple and a more direct approach is sufficient.</li><li>When your application needs a single source of truth.</li><li>When state-lifting to the top-level component no longer suffices.</li><li>When you need to persist state.</li></ul><h4># Advantages</h4><ul><li>Improves application maintainability by centralizing state update logic.</li><li>Facilitates debugging and tracking of state changes by having a single place where updates occur.</li><li>Promotes a more scalable and structured design, especially in applications with a large amount of state logic.</li></ul><h4># Disadvantages</h4><ul><li>Increased boilerplate and verbosity.</li><li>Steeper learning curve.</li><li>Potential performance issues.</li><li>Complexity in managing large-scale applications.</li><li>Debugging challenges.</li><li>Overhead for simple use cases.</li><li>Synchronous nature requires additional tools for side effects.</li></ul><h4># Example</h4><p>Now it’s time to examine the <strong>Reducer state pattern</strong> and how it operates. We’re going to implement a todo application with useReducer hook.</p><ul><li><strong>What is </strong><strong>useReducer?</strong></li></ul><p>A useReducer is a hook in React that allows you to add a reducer to your component. This hook takes a reducer function and an initialState as arguments. It also returns an array of the current state and a dispatch function.</p><pre>const [state, dispatch] = useReducer(reducer, initialState);</pre><p>Let’s familiarize ourselves with what the parameters mean:</p><p><strong>state</strong>: It represents the current value and is set to the initialState value during the initial render.</p><p><strong>dispatch</strong>: It is a function that updates the state value and always triggers a re-render, just like the updater function in useState.</p><p><strong>reducer</strong>: It is a function that houses all the logic of how the state gets updated. It takes state and action as arguments and returns the next state.</p><p><strong>initialState</strong>: It houses the initial value and can be any type.</p><ul><li><strong>Initial state</strong></li></ul><pre>const initialState = {<br>  todos: []<br>}</pre><ul><li><strong>Implementation of </strong><strong>Reducer function</strong></li></ul><p>The implementation in the below code snippet is about <strong>the</strong> <strong>reducer function </strong>which<strong> </strong>is always declared outside of components. It takes two parameters. The first one is state(current state), and the second one is action(An action is a plain object that typically has a type property which identifies a specific action. Actions describe what happens and contain information necessary for the reducer to update the state.). There is a switch case that determines which action has to be executed.</p><pre>// Reducing function to handle actions and update state<br>const reducer = (state, action) =&gt; {<br>  switch (action.type) {<br>    case &#39;ADD_TODO&#39;:<br>      return {<br>        ...state,<br>        todos: [<br>          ...state.todos,<br>          {<br>            id: state.todos.length + 1,<br>            text: action.payload,<br>            completed: false,<br>          },<br>        ],<br>      };<br>    case &#39;TOGGLE_TODO&#39;:<br>      return {<br>        ...state,<br>        todos: state.todos.map(todo =&gt;<br>          todo.id === action.payload<br>            ? { ...todo, completed: !todo.completed }<br>            : todo<br>        ),<br>      };<br>    case &#39;REMOVE_TODO&#39;:<br>      return {<br>        ...state,<br>        todos: state.todos.filter(todo =&gt; todo.id !== action.payload),<br>      };<br>    default:<br>      return state;<br>  }<br>};</pre><p>The reducer function has 3 cases with a few logic separately. All three cases are todos adding, toggling, and removing.</p><ul><li><strong>How does</strong><strong>dispatch function work?</strong></li></ul><p>Dispatch function returned by the useReducer hook and is responsible for updating the state to a new state. The dispatch function takes the only action as its argument. We can place the dispatch function inside an event handler function. You can see in the below code snippet, 3 handlers that dispatch 1 action individually. Every action has an object with a mandatory type and payload property.</p><pre><br><br>  const addTodo = (text) =&gt; {<br>    dispatch({ type: &#39;ADD_TODO&#39;, payload: text });<br>  };<br><br>  const toggleTodo = (id) =&gt; {<br>    dispatch({ type: &#39;TOGGLE_TODO&#39;, payload: id });<br>  };<br><br>  const removeTodo = (id) =&gt; {<br>    dispatch({ type: &#39;REMOVE_TODO&#39;, payload: id });<br>  };</pre><ul><li><strong>What happens behind the hood?</strong></li></ul><p>The action of clicking the button triggers a dispatch function that sends information of type to the reducer function. The dispatching (clicking of the button) causes a re-render of the component. The reducer function conditionally matches the case with the type from the action object and updates the state accordingly after evaluation has taken place.</p><p>The entire logic of our to-do app has been done. Now, we can return our JSX with the state to be displayed on the user interface and the handler functions passed on the onClick event handler for the buttons.</p><ul><li><strong>Now have a look at the JSX code.</strong></li></ul><pre>// Initial state<br>const initialState = {<br>  todos: []<br>}<br><br>// Example component using the State Reducer Pattern<br>const TodoList = () =&gt; {<br>  // Initialize the useReducer hook to manage state with the defined reducer<br>  .....<br><br>  // 3 Handler functions to handle user interactions<br>  .....<br><br>  // JSX code<br>  return (<br>    &lt;div&gt;<br>      &lt;h2&gt;Todo List&lt;/h2&gt;<br>      &lt;ul&gt;<br>        {state.todos.map(todo =&gt; (<br>          &lt;li key={todo.id}&gt;<br>            &lt;span<br>              style={{<br>                textDecoration: todo.completed ? &#39;line-through&#39; : &#39;none&#39;,<br>              }}<br>              onClick={() =&gt; toggleTodo(todo.id)}<br>            &gt;<br>              {todo.text}<br>            &lt;/span&gt;<br>            &lt;button onClick={() =&gt; removeTodo(todo.id)}&gt;Remove&lt;/button&gt;<br>          &lt;/li&gt;<br>        ))}<br>      &lt;/ul&gt;<br>      &lt;input<br>        type=&quot;text&quot;<br>        placeholder=&quot;Add todo...&quot;<br>        onKeyDown={e =&gt; {<br>          if (e.key === &#39;Enter&#39; &amp;&amp; e.currentTarget.value.trim() !== &#39;&#39;) {<br>            addTodo(e.currentTarget.value.trim());<br>            e.currentTarget.value = &#39;&#39;;<br>          }<br>        }}<br>      /&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default TodoList;</pre><h4># Conclusion</h4><p>We have covered what the <strong>State Reducer Pattern</strong> is, the <strong>advantages</strong> and <strong>disadvantages</strong> of this pattern, and how the useReducer hook operates with a whole to-do app.</p><p><strong><em>Thanks for reading.</em></strong><em> If you have any thoughts or suggestions, feel free to comment below.</em></p><p><em>You can follow me on </em><a href="https://x.com/noyon310197">Twitter</a>, <a href="https://github.com/NYN31">GitHub</a>, and <a href="https://www.linkedin.com/in/noyon31/">LinkedIn</a>.</p><p><strong><em>See you! 👋</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64cc375f220e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Pattern 01 - Singleton]]></title>
            <link>https://medium.com/@noyoncse3101/design-pattern-01-singleton-cb9db180cffe?source=rss-864e186c1d48------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb9db180cffe</guid>
            <category><![CDATA[singleton]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Md Sajjad Hosen Noyon]]></dc:creator>
            <pubDate>Tue, 02 Jul 2024 04:28:19 GMT</pubDate>
            <atom:updated>2024-10-27T10:39:49.487Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qWCzQJAdQrxpuDMm.png" /></figure><p>Singleton is a <strong>creational design pattern</strong> that lets you ensure that a class has only one instance while providing a global access point to this instance.</p><h3>Singleton pattern principles</h3><ol><li>Singleton’s design pattern ensures that a class has only one instance and must restrict the instantiation of the class to a single object.</li><li>It provides a global access point to the instance and allows other classes and components to access the Singleton instance easily.</li></ol><h3>Java singleton pattern implementation</h3><p>Implementing a singleton pattern, we have different approaches, but all of them have the following common concepts.</p><ul><li>Private constructor to restrict instantiation of the class from other classes.</li><li>Private static variable of the same class that is the only instance of the class.</li><li>Public static method that returns the instance of the class, this is the global access point for the outer world to get the instance of the singleton class.</li></ul><h3>1. Eager initialization</h3><p>In eager initialization, the singleton class instance is created during class loading.</p><pre>public class EagerInitializedSingleton {<br><br>    private static final EagerInitializedSingleton instance = new EagerInitializedSingleton();<br><br>    // private constructor to avoid client applications using the constructor<br>    private EagerInitializedSingleton(){}<br><br>    public static EagerInitializedSingleton getInstance() {<br>        return instance;<br>    }<br>}</pre><p>This guarantees that the instance is always available but may consume resources even if it’s not needed immediately.</p><h3>2. Lazy initialization</h3><p>Lazy instantiation defers the instantiation of the singleton instance when it is needed. This approach conserves resources.</p><pre>public class LazyInitializedSingleton {<br><br>    private static LazyInitializedSingleton instance;<br><br>    private LazyInitializedSingleton(){}<br><br>    public static LazyInitializedSingleton getInstance() {<br>        if (instance == null) {<br>            instance = new LazyInitializedSingleton();<br>        }<br>        return instance;<br>    }<br>}</pre><p>The implementation works fine in the case of a <strong>single-thread</strong> environment. Still, when it comes to a <strong>multi-thread system</strong>, it can cause issues if multiple threads are inside the if condition simultaneously. It will destroy the singleton pattern and both threads will get different instances of the singleton class.</p><h3>3. Thread-safe singleton</h3><p>The above example(Lazy initialization) of a singleton pattern is not thread-safe. To achieve thread safety, we can use the following approach.</p><ol><li><strong>Synchronize the getInstance() method.</strong></li></ol><p>For the thread-safe singleton pattern, you just need to use only a <strong>synchronized</strong> keyword on<strong> getInstead() </strong>method declaration. Here is the implementation</p><pre>public class ThreadSafeSingleton {<br><br>    private static ThreadSafeSingleton instance;<br><br>    private ThreadSafeSingleton(){}<br><br>    public static synchronized ThreadSafeSingleton getInstance() {<br>        if (instance == null) {<br>            instance = new ThreadSafeSingleton();<br>        }<br>        return instance;<br>    }<br><br>}</pre><h4>Pros</h4><ul><li>Thread safety is guaranteed.</li><li>The client application can pass the parameters.</li><li>Lazy initialization achieved.</li></ul><h4>Cons</h4><ul><li>Slow performance because of locking overhead.</li><li>Unnecessary synchronization that is not required once the instance variable is initialized.</li></ul><p><strong>2. Double-Checked Locking: Use the synchronized block inside the if block.</strong></p><p>Because of the locking overhead of getInstead() method, using a synchronized block inside the method instead of the <strong>synchronized </strong>keyword on method declarations is more faster and efficient. To make it efficient, double-check locking is very useful in that case.</p><pre>public class ThreadSafeSingleton {<br><br>    private static ThreadSafeSingleton instance;<br><br>    private ThreadSafeSingleton(){}<br>  <br>    public static ThreadSafeSingleton getInstanceUsingDoubleLocking() {<br>        if (instance == null) {<br>            synchronized (ThreadSafeSingleton.class) {<br>                if (instance == null) {<br>                    instance = new ThreadSafeSingleton();<br>                }<br>            }<br>        }<br>        return instance;<br>    }<br>}</pre><h4>Pros</h4><ul><li>Thread safety is guaranteed.</li><li>The client application can pass arguments.</li><li>Lazy initialization achieved.</li><li>Synchronization overhead is minimal and applicable only for the first few threads when the variable is null.</li></ul><h4>Cons</h4><ul><li>Extra if condition.</li></ul><h3>Advantage of the singleton pattern</h3><ol><li><strong>Single instance creation</strong></li><li><strong>Global Access</strong></li><li><strong>Lazy initialization</strong></li><li><strong>Thread safety</strong></li></ol><h3>Disadvantages of the singleton pattern</h3><ol><li><strong>Global state: </strong>Introducing a global state complicates system behavior tracking and potentially leads to bugs.</li><li><strong>Tight coupling: </strong>Direct access to the singleton can result in tight coupling, making future changes or replacements difficult.</li><li><strong>Testing challenges:</strong> Global access complicates unit testing.</li><li><strong>Lifecycle management:</strong> Managing the singleton lifecycle, especially for re-initialization can be complex.</li><li><strong>Limited extensibility:</strong> Extending or modifying Singleton classes can be challenging due to their restricted instantiation.</li><li><strong>Violate The single responsibility principle:</strong> The Singleton class has dual responsibilities. One is a single instance creation and another is task execution. So it violates the single responsibility principle.</li></ol><h3><strong>Few Real-word singleton Examples:</strong></h3><ol><li><strong>Logger</strong>: Manages logging operations across a system.</li><li>D<strong>atabase Connection: </strong>Provides a shared connection for database interactions.</li><li><strong>Configuration manager:</strong> Centralizes application settings and properties.</li><li><strong>Cache manager:</strong> Handles caching operations to improve performance.</li><li><strong>Thread pool:</strong> Manages thread creation and execution in concurrent programming.</li></ol><h3>Reference:</h3><ol><li><a href="https://www.digitalocean.com/community/tutorials/thread-safety-in-java-singleton-classes">https://www.digitalocean.com/community/tutorials/thread-safety-in-java-singleton-classes</a></li><li><a href="https://refactoring.guru/design-patterns/singleton">https://refactoring.guru/design-patterns/singleton</a></li><li><a href="https://belatrix.globant.com/us-en/blog/the-singleton-design-pattern/">https://belatrix.globant.com/us-en/blog/the-singleton-design-pattern/</a></li></ol><p><strong><em>Thanks for reading.</em></strong><em> If you have any thoughts or suggestions, feel free to comment below.</em></p><p><em>You can follow me on </em><a href="https://x.com/noyon310197">Twitter</a>, <a href="https://github.com/NYN31">GitHub</a>, and <a href="https://www.linkedin.com/in/noyon31/">LinkedIn</a>.</p><p><strong><em>See you! 👋</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb9db180cffe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Design Pattern Part 3: Render Props]]></title>
            <link>https://medium.com/@noyoncse3101/react-design-pattern-part-2-render-props-21e2c9a18747?source=rss-864e186c1d48------2</link>
            <guid isPermaLink="false">https://medium.com/p/21e2c9a18747</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[render-props]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Md Sajjad Hosen Noyon]]></dc:creator>
            <pubDate>Fri, 14 Jun 2024 15:31:59 GMT</pubDate>
            <atom:updated>2024-08-24T14:14:36.446Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*K_NwHMcYhl42c2gXUZaiPg.png" /></figure><p>The render props pattern in React is a powerful technique for sharing code between components. It involves using a prop whose value is a function. A component with a render prop takes this function, which returns a React element, and calls it instead of implementing its render logic. This pattern offers significant benefits, such as enhanced reusability and flexibility in your components, making your code more maintainable and easier to understand.</p><p>Let’s understand the basics. You have a component named Counter. Let’s put the render props pattern into action with a practical example. We’ll use it to share counter logic between two components: ClickCounter and HoverCounter. This real-world example, which you can relate to, will help you see the practicality and power of the render props pattern in solving real development challenges.</p><p>Don’t worry. We’ll break down the concept of render props into three parts to provide a clear and straightforward understanding, making the learning process easier and more manageable.</p><ol><li>View side components of click and hover counters.</li><li>The Counter component which takes the render function as a prop.</li><li>The calling side where Counter component called with a render function.</li></ol><h3>1. View Side Components</h3><p>ClickCounter Component:</p><pre>const ClickCounter = ({ count, incrementCount }) =&gt; {<br>  return (<br>    &lt;button type=&quot;button&quot; onClick={incrementCount}&gt;<br>      Clicked {count} times<br>    &lt;/button&gt;<br>  );<br>}</pre><ul><li>This component displays the number of times the button clicks.</li><li>It receives two props: count (the current count) and incrementCount (a function to increment the count).</li></ul><p><strong>HoverCounter Component:</strong></p><pre>const HoverCounter = ({ count, incrementCount }) =&gt; {<br>  return (<br>    &lt;h1 onMouseOver={incrementCount}&gt;<br>      Hovered {count} times<br>    &lt;/h1&gt;<br>  );<br>}</pre><ul><li>This component renders a heading that displays the number of times it has been hovered over.</li><li>It also receives the count and incrementCount props.</li></ul><h3>2. Counter Component with Render Props</h3><p><strong>Counter Component:</strong></p><pre>const Counter = ({ render }) =&gt; {<br>  const [count, setCount] = useState(0);<br><br>  const countHandler = () =&gt; {<br>    setCount(prev =&gt; prev + 1);<br>  };<br><br>  return render(count, countHandler);<br>};<br>export default Counter;</pre><ul><li>This component maintains the counterlogic.</li><li>It uses the useState hook to keep track of the count state.</li><li>The countHandler function increments the count state.</li><li>The render function is called and returned with the current count and the countHandler function, allowing any component to use this counterlogic.</li></ul><h3>3. Calling Side</h3><p><strong>App Component:</strong></p><pre>const App = () =&gt; {<br>  return (<br>    &lt;&gt;<br>      &lt;Counter<br>        render={(counter, incrementCount) =&gt; (<br>          &lt;ClickCounter count={counter} incrementCount={incrementCount} /&gt;<br>        )}<br>      /&gt;<br><br>      &lt;Counter<br>        render={(counter, incrementCount) =&gt; (<br>          &lt;HoverCounter count={counter} incrementCount={incrementCount} /&gt;<br>        )}<br>      /&gt;<br>    &lt;/&gt;<br>  );<br>};</pre><ul><li>The App component uses the Counter component twice with different render functions.</li><li>The first Counter component renders a ClickCounter, passing down the count and incrementCount as props.</li><li>The second Counter component renders a HoverCounter, also passing down the count and incrementCount as props.</li></ul><h4>When to use</h4><ul><li>It would be best to share logic between multiple components but don’t want to use higher-order components (HOCs) or don’t find them suitable for your use case.:</li><li>You need reusable functionality like form handling, data fetching, or animations.</li><li>React render props are handy when components need to be highly customizable, and you want to allow users to define how certain aspects of the component should render or behave.</li><li>When you need more control over the rendering process than HOCs provide.</li></ul><h4>When Not to Use</h4><p>The render props pattern might not be suitable in the following situations:</p><ul><li><strong>Simple use cases</strong>: If your component logic is simple, using render props can add unnecessary complexity.</li><li><strong>Performance concerns</strong>: Excessive use of render props can lead to many of function calls, potentially affecting performance.</li><li><strong>Readability</strong>: Too many nested render prop components can make your code harder to read and maintain.</li></ul><h4>Advantages</h4><ul><li><strong>Reusability</strong>: Multiple components can share logic without duplication..</li><li><strong>Flexibility</strong>: Components using render props can be easily customized, allowing for more dynamic rendering and empowering you to create elements that suit your needs.</li><li><strong>Separation of Concerns</strong>: Keeps logic and UI concerns separate, making the components easier to understand and maintain.</li></ul><h4>Disadvantages</h4><ul><li><strong>Complexity</strong>: Introduces additional complexity, making the code harder to read, especially for those unfamiliar with the pattern.</li><li><strong>Performance</strong>: This can lead to performance issues due to the creation of new functions on every render.</li><li><strong>Verbosity</strong>: Render Props can make the component structure more verbosed, especially with deeply nested components.</li></ul><h4>Example</h4><p>Let’s create a simple example using the Render Props pattern to display a collection of products in different locations of our application.</p><p>First, let’s declare a list of products:</p><pre>export const allProducts = [<br>  {<br>    id: 1,<br>    title: &#39;Product 1&#39;,<br>    description: &#39;This is product 1&#39;,<br>  },<br>  {<br>    id: 2,<br>    title: &#39;Product 2&#39;,<br>    description: &#39;This is product 2&#39;,<br>  },<br>  {<br>    id: 3,<br>    title: &#39;Product 3&#39;,<br>    description: &#39;This is product 3&#39;,<br>  },<br><br>  // ...<br>];</pre><p>Then, let’s create theProducts component that uses the render props pattern:</p><pre>const Products = ({ render }) =&gt; {<br>  // Fetching products can be done here.<br>  // or use allProducts hard coded data<br>  const products = allProducts;<br><br>  return render(products);<br>};</pre><p>In the Products component, render is a function that renders the products. This function allows you to customize the rendering of the products when you use the Products component. It’s a vital part of the render props pattern, demonstrating how a component can delegate control over its rendering to a parent component.</p><p>For example, you can use the Products component in two different locations in your application and display the products in different ways:</p><pre>const HomePage = () =&gt; {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Products List&lt;/h1&gt;<br>      &lt;Products<br>        render={products =&gt; (<br>          &lt;ul&gt;<br>            {products?.map(product =&gt; (<br>              &lt;li key={product.id}&gt;{product.title}&lt;/li&gt;<br>            ))}<br>          &lt;/ul&gt;<br>        )}<br>      /&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default HomePage;<br><br>const ProductsSection = () =&gt; {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Products List&lt;/h1&gt;<br>      &lt;Products<br>        render={products =&gt; (<br>          &lt;div&gt;<br>            {products?.map(product =&gt; (<br>              &lt;div key={product.id}&gt;<br>                &lt;h2&gt;{product.title}&lt;/h2&gt;<br>                &lt;p&gt;{product.description}&lt;/p&gt;<br>              &lt;/div&gt;<br>            ))}<br>          &lt;/div&gt;<br>        )}<br>      /&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default ProductsSection;</pre><p>In this example, the first use of the Products component displays the products as a list of titles, while the second use displays their titles and descriptions.</p><p>This approach allows you to reuse the Products component and customize its rendering according to your needs in different parts.</p><p>Some popular libraries that use the Render Props pattern include: React Router, Formik, Downshift.</p><h4>Conclusion</h4><p>The Render Props pattern in React is a powerful, flexible design approach that enhances component reusability and composability.</p><p>By passing a function as a prop to a component, developers can delegate control over the rendering logic to the parent component, enabling a more dynamic and customizable behavior.</p><h4>Reference</h4><ol><li><a href="https://javascriptpatterns.vercel.app/patterns/react-patterns/render-props">https://javascriptpatterns.vercel.app/patterns/react-patterns/render-props</a></li><li><a href="https://legacy.reactjs.org/docs/render-props.html">https://legacy.reactjs.org/docs/render-props.html</a></li></ol><p><strong><em>Thanks for reading.</em></strong><em> If you have any thoughts or suggestions, feel free to leave a comment below.</em></p><p><em>You can follow me on </em><a href="https://x.com/noyon310197">Twitter</a>, <a href="https://github.com/NYN31">GitHub</a>, and <a href="https://www.linkedin.com/in/noyon31/">LinkedIn</a>.</p><p><strong><em>See you! 👋</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=21e2c9a18747" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Searching (Linear search and Binary search)]]></title>
            <link>https://medium.com/@noyoncse3101/searching-linear-search-and-binary-search-b6de5a35efc1?source=rss-864e186c1d48------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6de5a35efc1</guid>
            <category><![CDATA[cplusplus]]></category>
            <category><![CDATA[binary-search]]></category>
            <category><![CDATA[linear-search]]></category>
            <category><![CDATA[searching]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Md Sajjad Hosen Noyon]]></dc:creator>
            <pubDate>Sat, 25 May 2024 15:40:29 GMT</pubDate>
            <atom:updated>2024-06-13T17:02:52.686Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*lONVcsODqLuZfP0x.jpg" /></figure><p><strong># Story / Scenario</strong></p><p>Let&#39;s say, employees of Exabyting Technologies are going on a tour in a tourist place. They’re staying in a hotel and booked rooms for every employee. For every employee, they fixed the floor by their ID. Suppose, someone has ID: SE026DHK. So, he will stay on the 26th floor and none others. So, employees with the highest IDs stay on the topmost floor and the lowest IDs remain on the lower floor.</p><p>Now, the hotel authority has two boys for servicing the employees. For any service, employees call these two boys and the boys help them find the floor number by the employee ID. In the following way, the boys find the room and floor described below:</p><p><strong>1st Boy:</strong> When he gets the ID, he tries to find out the information of the employee by going through it one by one until he finds out. So, every time he needs to find out any information about the employee, he goes through the whole list of employees.</p><p><strong>2nd Boy:</strong> He is smart and intelligent. As he knows the employee&#39;s rooms are on every floor in a sorted manner, he doesn’t go through the whole list. He tries to find out the middle of the employee details from the list and tries to match the employee in the middle is he looking for. If it’s not the employee, the boy decides to go left or right side according to ID. By using this technique, he saves his time and effort both compared to 1st Boy.</p><p><strong># Searching</strong></p><p>Searching, in the context of computer science and information retrieval, is the process of finding specific data or information within a collection of data. This process can be applied to various types of data structures, databases, files, or the web. Today, I’ll discuss two types of searching: (1) Linear search, and (2) Binary search.</p><p><strong># Linear Search</strong></p><p>Also known as sequential search, it involves checking each element in a list or array one by one until the desired element is found or the list ends. In the above situation, the first boy’s search is linear. Though the implementation is easy, the time complexity it’s poor. The whole list has to be iterated to find the desired items.</p><pre>#include &lt;iostream&gt;<br>using namespace std;<br><br>int linearSearch(int arr[], int size, int target) {<br>    for (int i = 0; i &lt; size; i++) {<br>        if (arr[i] == target) {<br>            return i;  // Return the index of the target element<br>        }<br>    }<br>    return -1;  // Return -1 if the target element is not found<br>}<br><br>int main() {<br>    int arr[] = {10, 25, 30, 45, 50};<br>    int size = sizeof(arr) / sizeof(arr[0]);<br>    int target = 30;<br>    int result = linearSearch(arr, size, target);<br><br>    if (result != -1) {<br>        cout &lt;&lt; &quot;Element found at index &quot; &lt;&lt; result &lt;&lt; endl;<br>    } else {<br>        cout &lt;&lt; &quot;Element not found in the array&quot; &lt;&lt; endl;<br>    }<br><br>    return 0;<br>}</pre><p><strong>Explanation:</strong></p><ul><li>The function linearSearch iterates through each element of the array.</li><li>If it finds the target element, it returns the index.</li><li>If it reaches the end of the array without finding the target, it returns -1.</li></ul><p><strong>Complexity:</strong></p><ul><li>Time Complexity: O(N)</li><li>Space Complexity: O(1)</li></ul><p><strong># Binary Search</strong></p><p>Binary search is the technique of searching in the middle. Unlike linear search, it does not search the whole list. The prerequisites of binary search are the array must be sorted and every element can be accessible by index. If these match, this algorithm finds from the middle based on the target value and cuts the left or right half of the list. Because of omitting half the list in every iteration, this algorithm is called binary search and the complexity is reduced dramatically.</p><pre>#include &lt;iostream&gt;<br>using namespace std;<br><br>int binarySearch(int arr[], int size, int target) {<br>    int left = 0;<br>    int right = size - 1;<br><br>    while (left &lt;= right) {<br>        int mid = left + (right - left) / 2;<br><br>        // Check if the target element is at the middle<br>        if (arr[mid] == target) {<br>            return mid;<br>        }<br><br>        // If the target element is greater, ignore the left half<br>        if (arr[mid] &lt; target) {<br>            left = mid + 1;<br>        }<br>        // If the target element is smaller, ignore the right half<br>        else {<br>            right = mid - 1;<br>        }<br>    }<br><br>    return -1;  // Return -1 if the target element is not found<br>}<br><br>int main() {<br>    int arr[] = {10, 20, 30, 40, 50};<br>    int size = sizeof(arr) / sizeof(arr[0]);<br>    int target = 30;<br>    int result = binarySearch(arr, size, target);<br><br>    if (result != -1) {<br>        cout &lt;&lt; &quot;Element found at index &quot; &lt;&lt; result &lt;&lt; endl;<br>    } else {<br>        cout &lt;&lt; &quot;Element not found in the array&quot; &lt;&lt; endl;<br>    }<br><br>    return 0;<br>}</pre><p><strong>Explanation:</strong></p><ul><li>The function binarySearch starts with two-pointers, left and right, representing the bounds of the array.</li><li>It calculates the middle index and compares the middle element with the target.</li><li>If the middle element is equal to the target, it returns the index.</li><li>If the target is greater than the middle element, it narrows the search to the right half of the array.</li><li>If the target is less than the middle element, it narrows the search to the left half of the array.</li><li>This process continues until the target is found or the search interval is empty.</li></ul><p><strong>Complexity:</strong></p><ul><li>Time Complexity: O(logn)</li><li>Space Complexity: O(1)</li></ul><p><strong># Few problems with binary search</strong></p><ol><li><a href="https://leetcode.com/problems/search-insert-position/description/">Search insertion position</a></li><li><a href="https://leetcode.com/problems/sqrtx/description/">Sqrt(x)</a></li><li><a href="https://leetcode.com/problems/search-in-rotated-sorted-array/description/">Search in a rotated sorted array</a></li><li><a href="https://leetcode.com/problems/find-peak-element/description/">Find peak element</a></li></ol><p><strong><em>Thanks for reading.</em></strong><em> If you have any thoughts or suggestions, feel free to leave a comment below.</em></p><p><em>You can follow me on </em><a href="https://x.com/noyon310197">Twitter</a> , <a href="https://github.com/NYN31">Github</a> and <a href="https://www.linkedin.com/in/noyon31/">LinkedIn</a>.</p><p><strong><em>See you! 👋</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6de5a35efc1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Design Pattern Part 2: HOC]]></title>
            <link>https://medium.com/@noyoncse3101/react-design-pattern-part-2-hoc-53ae507f0bb4?source=rss-864e186c1d48------2</link>
            <guid isPermaLink="false">https://medium.com/p/53ae507f0bb4</guid>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[học]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Md Sajjad Hosen Noyon]]></dc:creator>
            <pubDate>Thu, 23 May 2024 13:58:51 GMT</pubDate>
            <atom:updated>2024-07-09T07:52:56.268Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AHDlzPuscNF_RvO1cxsyDQ.png" /></figure><p>We often want to use the same logic in multiple components within our application, so we reduce code duplication as much as possible. One way to do this and make code logic reusable is using one of the React design patterns, the <strong>Higher Order Component(HOC)</strong>.</p><p>One of the empowering features of an HOC is its flexibility. Its function can take a component and return a new component with additional or extended functionality, giving us the control to modify our components according to our needs.</p><p><strong># When to use it</strong></p><ul><li>Need to share logic between multiple components without duplicating code.</li><li>To add common behaviors or features to multiple components.</li><li>Need to isolate presentation logic from business logic in a component.</li></ul><p><strong># When not to use it</strong></p><ul><li>When the logic is specific to a single component.</li><li>When the logic is too complex, it may make understanding HOCs challenging.</li></ul><p><strong># Advantages</strong></p><ul><li>Promotes code reuse by encapsulating and sharing logic between components.</li><li>HOCs allow a clear separation of presentation logic from business logic, bringing clarity and efficiency to our code.</li><li>Applying functional design patterns facilitates code composition(combining smaller, independent components to create complex UIs) and modularity.</li></ul><p><strong># Disadvantages</strong></p><ul><li>May introduce an additional layer of abstraction that makes it difficult to track data flow.</li><li>Excessive composition of HOCs can generate complex components that are difficult to debug.</li><li>Sometimes, it can hide the component hierarchy, making it difficult to understand how the application is structured.</li></ul><p><strong># Example 1:</strong></p><p>In the below example, there are two counters: ClickCounter and HoverCounter. The two components have the same logic for counting their values by 1. So, WithCounter(HOC) contains a component as a parameter with the logic of both counter and return a new component.</p><pre>const ClickCounter = ({ count, incrementCount }) =&gt; {<br> return (<br>  &lt;div&gt;<br>  &lt;button type=&quot;button&quot; onClick={incrementCount}&gt;<br>   Clicked {count} times.<br>  &lt;/button&gt;<br>  &lt;/div&gt;<br> );<br>}<br><br>export default withCounter(ClickCounter);</pre><p>The above component is ClickCounter which takes props with counter state and counter handler from WithCounter. With every click, the counter value increased by 1.</p><pre>const HoverCounter = ({ count, incrementCount }) =&gt; {<br> const { count, incrementCount } = props;<br><br> return (<br>  &lt;div&gt;<br>  &lt;button onMouseOver={incrementCount}&gt;<br>   Hoverd {count} times.<br>  &lt;/button&gt;<br>  &lt;/div&gt;<br> );<br>}<br><br>export default withCounter(HoverCounter);</pre><p>The above component is HoverCounter, which takes props with counter state and counter handler from WithCounter. With every hover, the counter value increased by 1.</p><pre>const withCounter = (OriginalComponent) =&gt; {<br> function NewCounter(props){<br>  const [count, setCount] = useState(0);<br>  <br>  const incrementCount = () =&gt; {<br>   setCount(prev =&gt; prev + 1);<br>  }<br><br>  return (<br>    &lt;OriginalComponent<br>      {...props}<br>      count={count}<br>      incrementCount={incrementCount}<br>    /&gt;<br>  );<br> };<br><br> return NewCounter;<br>}</pre><p>The above function is WithCounter, our HOC takes a component named OriginalComponent as a parameter. An inner function that has the main logic and handler, returns as a props with OriginalComponent . Then WithCounter return its inner function component.</p><p><strong># Example 2</strong></p><p>We want to create a HOC that handles the state and methods for submitting it from a form. The HOC will handle the form values, validate the data, and send the request to the server.</p><pre>// HOC that handles form state and logic<br>function withForm({ OriginalComponent }) {<br>  const NewForm = (props) =&gt; {<br>    const [formValues, setFormValues] = useState({});<br><br>    const handleInputChange = event =&gt; {<br>      const { name, value } = event.target;<br>      setFormValues(prevValues =&gt; ({<br>        ...prevValues,<br>        [name]: value,<br>      }));<br>    };<br><br>    const handleSubmit = event =&gt; {<br>      event.preventDefault();<br>      props.onSubmit(formValues);<br>    };<br><br>    return (<br>      &lt;OriginalComponent<br>        {...props}<br>        formValues={formValues}<br>        onInputChange={handleInputChange}<br>        onSubmit={handleSubmit}<br>      /&gt;<br>    );<br>  };<br><br>  return NewForm;<br>}</pre><pre>const LoginForm = ({ formValues, onInputChange, onSubmit }) =&gt; {<br>  return (<br>    &lt;form onSubmit={onSubmit}&gt;<br>      &lt;input<br>          type=&quot;text&quot;<br>          name=&quot;name&quot;<br>          value={formValues.name || &#39;&#39;}<br>          onChange={onInputChange}<br>       /&gt;<br>       &lt;input<br>          type=&quot;text&quot;<br>          name=&quot;email&quot;<br>          value={formValues.email || &#39;&#39;}<br>          onChange={onInputChange}<br>        /&gt;<br>        &lt;button type=&quot;submit&quot;&gt;Enviar&lt;/button&gt;<br>    &lt;/form&gt;<br>  );<br>};<br><br>// Using the HOC to wrap the MyForm component<br>const LoginFormWithLogic = withForm(MyForm);</pre><pre>// Main component that renders the form<br>const App: React.FC = () =&gt; {<br>  const handleSubmit = (values: FormValues) =&gt; {<br>    console.log(&#39;Form values:&#39;, values);<br>    // Logic to send the form data to the server<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;HOC Form&lt;/h1&gt;<br>      &lt;FormWithLogic onSubmit={handleSubmit} /&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default App;</pre><p><strong># Naming Conventions</strong></p><p>We have seen many examples of higher-order components in this blog post. You might have noticed the HOCs being with the word with .</p><p>withForm , withCounter , withErrorBoundary, withTranslationetc do not have strict naming conventions, but it is a good practice to prefix the HOC with the keyword with.</p><p>The new component that we create after wrapping them with the HOC should contain the name of the HOC to indicate that this component has been enhanced with an HOC.</p><p>For example, we had created a HOC withTranslation and a component called the LoginComponent and our enhanced component was called LoginComponentWithTranslation</p><pre>const LoginComponentWithTranslation = withTranslation(LoginComponent, i18n);</pre><p><strong># Common use cases of HOC</strong></p><ol><li>Management of state and handling of async data</li><li>Conditional rendering: Authorization and feature toggle</li><li>Translation and language switching</li><li>Error Boundary</li></ol><p><strong>NOTE:</strong> For more details, see references.</p><p><strong># Conclusion</strong></p><p>In this blog post, we have learned what higher-order components are and how to create simple higher-order components.</p><p>We have also observed scenarios where developers commonly use higher-order components.</p><p>This post will give you a good understanding of how and where to use higher-order components in your application.</p><p><strong># Reference</strong></p><ol><li><a href="https://deadsimplechat.com/blog/higher-order-componets-in-react/">https://deadsimplechat.com/blog/higher-order-componets-in-react/</a></li><li><a href="https://www.patterns.dev/react/hoc-pattern/">https://www.patterns.dev/react/hoc-pattern/</a></li></ol><p><strong><em>Thanks for reading.</em></strong><em> If you have any thoughts or suggestions, feel free to leave a comment below.</em></p><p><em>You can follow me on </em><a href="https://x.com/noyon310197">Twitter</a> , <a href="https://github.com/NYN31">Github</a> and <a href="https://www.linkedin.com/in/noyon31/">LinkedIn</a>.</p><p><strong><em>See you! 👋</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53ae507f0bb4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>