<?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 John Kamau on Medium]]></title>
        <description><![CDATA[Stories by John Kamau on Medium]]></description>
        <link>https://medium.com/@johnnyJK?source=rss-e496b7ee65a2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ARU31RRkbonGKXIX8LjPHw.jpeg</url>
            <title>Stories by John Kamau on Medium</title>
            <link>https://medium.com/@johnnyJK?source=rss-e496b7ee65a2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 23:17:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@johnnyJK/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[Asynchronous JavaScript: Callbacks, Promises, and Async/Await]]></title>
            <link>https://medium.com/@johnnyJK/asynchronous-javascript-callbacks-promises-and-async-await-2ca1d42016ef?source=rss-e496b7ee65a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ca1d42016ef</guid>
            <category><![CDATA[callback]]></category>
            <category><![CDATA[callbacks-vs-promises]]></category>
            <category><![CDATA[asyncawait]]></category>
            <category><![CDATA[promises]]></category>
            <category><![CDATA[asynchronous-javascript]]></category>
            <dc:creator><![CDATA[John Kamau]]></dc:creator>
            <pubDate>Tue, 04 Jun 2024 10:44:47 GMT</pubDate>
            <atom:updated>2024-06-27T10:24:27.875Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gO0CyiWvB_rB0yjTYFbPOg.png" /></figure><h3>Introduction</h3><p>One of the most powerful features of the JavaScript language is the ability to handle asynchronous operations. Asynchronous programming allows developers to perform tasks like fetching data from a server or reading a file without blocking the main execution thread. This ensures that applications remain responsive and efficient, providing a smoother user experience and better performance.</p><h3>Basics of Asynchronous Programming</h3><p>In programming, operations can be either synchronous or asynchronous. Understanding the difference between these two types is crucial for effective programming.</p><h4><strong>Synchronous Programming</strong></h4><p>Synchronous programming blocks the execution of subsequent code until the current operation completes. This means that each task is performed one after the other, waiting for the previous one to finish.</p><p>Consider a scenario where you need to book a flight, reserve a hotel room, and rent a car for a trip. In a synchronous world, you would call each service one by one, waiting on hold until each booking is confirmed before moving to the next. This approach can be problematic in certain situations, particularly when dealing with tasks that take a significant amount of time to complete.</p><p>A good example is when a synchronous program performs a task that requires waiting for a response from a remote server. The program will be stuck waiting for the response and cannot do anything else until the response is returned. This is known as<em> blocking</em>, and it can lead to the application appearing unresponsive or “frozen” to the user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_7ovEvnCQ-Ejtc5BXrUV4w.png" /><figcaption>synchronous operations</figcaption></figure><h3>Asynchronous Programming</h3><p>In contrast, asynchronous programming allows the execution of subsequent code to proceed independently while waiting for the current operation to complete.</p><p>Using the same scenario where you need to book a flight, reserve a hotel room, and rent a car for a trip, in an asynchronous world, you could call all three services simultaneously. While waiting for each service to confirm your booking, you can continue with other trip preparations, making the overall process faster and more efficient.</p><p>Asynchronous programming allows a program to continue working on other tasks while waiting for external events, such as network requests, to occur. For example, while a program retrieves data from a remote server, it can continue to execute other tasks such as responding to user inputs. This greatly improves the performance and responsiveness of a program.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*uJDg8QWxzQQmtDnJqhq5tg.png" /><figcaption>asynchronous operations</figcaption></figure><h3>Handling Asynchronous Operations</h3><p>In JavaScript, asynchronous programming can be achieved through a variety of techniques. In this article, we are going to cover ways in which you can do this.</p><h3>Using Callbacks</h3><p>Callbacks are one of the oldest and most widely used methods for handling asynchronous operations in JavaScript. A callback function is simply a function that is passed as an argument to another function and is executed after the completion of a task.</p><pre>// Declare function<br>function fetchData(callback) {<br>  setTimeout(() =&gt; {<br>    const data = {name: &quot;John&quot;, age: 24};<br>    callback(data);<br>  }, 3000);<br>}<br><br>// Execute function with a callback<br>fetchData(function(data) {<br>  console.log(data);<br>});<br><br>console.log(&quot;Data is being fetched...&quot;);</pre><p>In this example:</p><ul><li>We declare a function named fetchData that takes a callback function as an argument.</li><li>Inside fetchData, the setTimeout function is used to simulate an asynchronous operation by delaying the execution of a callback function for 3 seconds.</li><li>After the 3-second delay, the callback function passed to fetchData is invoked with a mock data object as its argument.</li><li>The callback function passed to fetchData is an anonymous function that logs the received data object to the console.</li><li><strong>Output:</strong> Initially, a message “Data is being fetched…” is logged to the console. After 3 seconds, the mock data object is fetched, and the callback function is executed, logging the data object to the console.</li></ul><p>Callbacks are powerful because they allow us to continue with other tasks while waiting for asynchronous operations to complete. However, they can lead to callback hell, a situation where multiple nested callbacks make the code difficult to read and maintain.</p><pre>getData(function(data1) {<br>    processData1(data1, function(data2) {<br>        processData2(data2, function(data3) {<br>            processData3(data3, function(data4) {<br>                // and so on...<br>            });<br>        });<br>    });<br>});</pre><p>In this example, each asynchronous operation depends on the result of the previous one, leading to deeply nested callbacks. As more operations are added, the code becomes increasingly difficult to manage, often resulting in bugs and decreased readability.</p><p>Despite their drawbacks, callbacks are still widely used, especially in older codebases and libraries. Understanding how to use callbacks effectively is essential for any JavaScript developer.</p><h3>Using Promises</h3><p>Promises provide a more elegant way to handle asynchronous operations compared to callbacks. A Promise represents a value that may be available now, in the future, or never. Promises have three states: Pending, Fulfilled, and Rejected.</p><pre>function fetchData() {<br>    return new Promise((resolve, reject) =&gt; {<br>        setTimeout(() =&gt; {<br>            const data = {name: &quot;John&quot;, age: 24};<br>            resolve(data);<br>        }, 3000);<br>    });<br>}<br><br>fetchData().then(console.log).catch(console.error);</pre><p>In this example, the fetchData function returns a Promise. Inside the Promise constructor, an asynchronous operation is simulated using setTimeout. Once the operation is complete, the resolve function is called with the fetched data.</p><p>Promises allow for chaining using the then method, making it easy to perform sequential asynchronous operations. Additionally, error handling is simplified with the catch method, which handles any errors that occur during the execution of the Promise chain.</p><h4>Async/Await: Simplifying Asynchronous Code</h4><p>Async/Await is a powerful feature in JavaScript that simplifies asynchronous programming by providing a more synchronous-looking syntax. While it builds on top of Promises, it offers a more intuitive way to handle asynchronous operations without directly dealing with Promise chains.</p><pre>function fetchData() {<br>    return new Promise((resolve, reject) =&gt; {<br>        setTimeout(() =&gt; {<br>            const data = {name: &quot;John&quot;, age: 24};<br>            resolve(data);<br>        }, 3000);<br>    });<br>}<br><br>async function getData() {<br>    try {<br>        const data = await fetchData();<br>        console.log(data);<br>    } catch (error) {<br>        console.error(error);<br>    }<br>}<br><br>getData();</pre><p>Here, the fetchData function returns a Promise, as it did before. However, instead of chaining .then() and .catch() methods, the getData function is defined as an async function. Inside getData, the await keyword is used to pause the execution until the fetchData Promise resolves, making the asynchronous code flow appear synchronous.</p><p>Using Async/Await simplifies error handling with traditional try/catch blocks, providing a more natural way to handle errors in asynchronous code. Overall, Async/Await makes asynchronous programming in JavaScript more readable and maintainable by allowing developers to write asynchronous code that looks and behaves like synchronous code.</p><h3>Practical Applications of Asynchronous JavaScript</h3><p>Asynchronous JavaScript is essential for creating responsive and efficient applications. Here are some practical applications where asynchronous operations play a crucial role:</p><h4><strong>1.Fetching Data from APIs</strong></h4><p>Applications often need to retrieve data from external APIs. Asynchronous operations allow the application to continue running while waiting for the data to be fetched.</p><pre>async function fetchUserData() {<br>    try {<br>        const response = await fetch(&#39;https://api.example.com/user&#39;);<br>        const data = await response.json();<br>        console.log(data);<br>    } catch (error) {<br>        console.error(&#39;Error fetching user data:&#39;, error);<br>    }<br>}<br><br>fetchUserData();</pre><p>In this example, the fetch API is used to retrieve user data. The await keyword ensures the code waits for the response before proceeding, without blocking the main thread.</p><h4>2.<strong>File Operations</strong></h4><p>When working with files, such as reading or writing to the file system, asynchronous operations are essential to prevent the main thread from freezing.</p><pre>const fs = require(&#39;fs&#39;);<br><br>fs.readFile(&#39;file.txt&#39;, &#39;utf8&#39;, (err, data) =&gt; {<br>  if (err) {<br>    console.error(&#39;Error reading file:&#39;, err);<br>    return;<br>  }<br>  console.log(&#39;File contents:&#39;, data);<br>});<br><br>console.log(&#39;This message will be printed first&#39;);</pre><p>In this example, when fs.readFile() is called, Node.js initiates the file read operation but doesn&#39;t wait for it to complete. Instead, it registers the provided callback function and immediately continues executing the next line, which logs the message &#39;This message will be printed first&#39;. When the file read operation completes, Node.js places the callback function in the event queue, and the event loop eventually dequeues and executes it on the main thread, logging the file contents or an error message.</p><p>By using asynchronous programming for file operations, the main execution thread remains responsive and can handle other tasks while waiting for the file operation to complete.</p><h4>3.Timers</h4><p>JavaScript provides the setTimeout and setInterval functions for scheduling code execution after a specified delay or at regular intervals, respectively. These functions are asynchronous, meaning they don&#39;t block the main execution thread while waiting for the specified time to elapse.</p><pre>// Scheduling a recurring execution every second<br>const intervalId = setInterval(() =&gt; {<br>  console.log(&#39;This message will be displayed every second&#39;);<br>}, 1000);<br><br>// After 5 seconds, stop the recurring execution<br>setTimeout(() =&gt; {<br>  clearInterval(intervalId);<br>  console.log(&#39;Interval cleared&#39;);<br>}, 5000);</pre><p>In this example, we store the identifier returned by setInterval in the intervalId variable. After 5 seconds (using setTimeout), we call clearInterval(intervalId), which stops the recurring execution scheduled by setInterval.</p><p>The clearInterval function is useful when you want to stop a recurring task based on certain conditions, such as user interactions, state changes, or timers. Without clearInterval, the recurring execution would continue indefinitely unless the page is reloaded or the script is terminated.</p><h4>4.Animations</h4><p>Creating smooth animations is another important use case for asynchronous JavaScript. The requestAnimationFrame function is designed specifically for this purpose. It tells the browser to update an animation before the next repaint, ensuring optimal performance and efficient use of system resources.</p><pre>const element = document.getElementById(&#39;myElement&#39;);<br>let position = 0;<br><br>function animateElement() {<br>  position += 10; // Update the position<br>  element.style.left = `${position}px`; // Move the element<br><br>  // Request the next animation frame<br>  if (position &lt; 500) {<br>    requestAnimationFrame(animateElement);<br>  }<br>}<br><br>// Start the animation<br>requestAnimationFrame(animateElement);</pre><p>In this example, the animateElement function is recursively called using requestAnimationFrame until the desired position is reached. The browser handles these function calls asynchronously, ensuring that the animation runs smoothly without blocking the main execution thread, ensuring a seamless user experience in web applications.</p><h4><strong>5.Event Handling</strong></h4><p>Event handling in the browser is inherently asynchronous, as events are triggered by user interactions or other external factors.</p><pre>const button = document.getElementById(&#39;myButton&#39;);<br><br>button.addEventListener(&#39;click&#39;, () =&gt; {<br>  console.log(&#39;Button clicked!&#39;);<br>});<br><br>console.log(&#39;This message will be displayed first&#39;);</pre><p>In this example, when the script runs, it logs the message &#39;This message will be displayed first&#39; to the console immediately. However, the event handler function (() =&gt; { console.log(&#39;Button clicked!&#39;); }) is not executed until the user actually clicks the button.</p><p>When the user clicks the button, the browser generates a click event and adds it to the event queue. The event loop detects the event in the queue and executes the registered event handler function, which logs the message &#39;Button clicked!&#39; to the console.</p><p>This asynchronous nature of event handling ensures that the JavaScript code doesn’t block the main execution thread while waiting for user interactions or other external events. The browser can continue to update the UI, parse HTML, execute other scripts, and perform other tasks while waiting for events to occur.</p><h3>Conclusion</h3><p>The practical applications discussed are indeed among the most important and widely-used cases where asynchronous JavaScript is employed. However, these examples do not represent an exhaustive list.</p><p>It is crucial to recognize that asynchronous programming is a widespread concept that finds applications in numerous other scenarios within the constantly evolving field of web development and beyond. As new technologies and use cases emerge, the significance of asynchronous programming in JavaScript is likely to continue increasing, ensuring efficient, responsive, and scalable applications across various domains.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ca1d42016ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding SQL Joins: A Comprehensive Guide]]></title>
            <link>https://medium.com/@johnnyJK/understanding-sql-joins-a-comprehensive-guide-88bab3457270?source=rss-e496b7ee65a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/88bab3457270</guid>
            <category><![CDATA[leftjoin]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[right-join]]></category>
            <category><![CDATA[sql-joins]]></category>
            <category><![CDATA[sql-inner-join]]></category>
            <dc:creator><![CDATA[John Kamau]]></dc:creator>
            <pubDate>Sat, 25 May 2024 12:14:21 GMT</pubDate>
            <atom:updated>2024-05-25T12:14:21.219Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*_swVOyX_rvqlFta_tXOzmQ.png" /><figcaption>SQL joins</figcaption></figure><p>SQL (Structured Query Language) is a powerful tool used for managing and manipulating relational databases. One of the most fundamental and essential features of SQL is the ability to join tables. Joins allow us to combine rows from two or more tables based on a related column between them.</p><p>In this article we will explore the different types of SQL joins, their syntax, and examples to help you understand how to use them effectively.</p><h3>What Are Joins?</h3><p>In SQL, joins are operations used to combine rows from two or more tables based on a related column between them. Joins are essential in relational databases because they allow you to retrieve data that is spread across multiple tables and present it in a unified way. This is particularly useful in normalized databases where related data is stored in separate tables to reduce redundancy and improve data integrity.</p><h3>Why Use Joins?</h3><ol><li><strong>Data Normalization:</strong> In relational databases, data is often divided into multiple tables to eliminate redundancy. Joins allow you to reassemble this data as needed.</li><li><strong>Complex Queries:</strong> Joins enable complex queries that can extract meaningful insights from multiple related tables.</li><li><strong>Data Integrity:</strong> By linking tables through joins, you maintain data integrity and consistency, ensuring that related data is accurate and synchronized.</li></ol><h3>Types of SQL Joins</h3><p>There are various types of SQL joins. Let’s explore some of the most widely used ones:</p><h3>1.INNER JOIN</h3><p>An INNER JOIN is one of the most commonly used joins in SQL. It returns only the rows that have matching values in both tables. If there is no match, the row is not included in the result set.</p><p>The INNER JOIN essentially combines the data from two or more tables based on a related column, and it filters out rows that do not satisfy the join condition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*Rnqyag9YjgwfHrYF1oXoow.png" /><figcaption>inner join</figcaption></figure><h4>Syntax of INNER JOIN</h4><pre>SELECT columns<br>FROM table1<br>INNER JOIN table2<br>ON table1.common_column = table2.common_column;</pre><ul><li>table1 and table2 are the names of the tables you want to join.</li><li>common_column is the column that exists in both tables and is used as the join condition.</li><li>columns are the columns you want to select in the result set.</li></ul><h4>Example of INNER JOIN</h4><p>Let’s consider two example tables: Employees and Departments.</p><p>employees table:</p><pre>| id | name    | department_id |<br>|----|---------|---------------|<br>| 1  | Alice   | 1             |<br>| 2  | Bob     | 2             |<br>| 3  | Charlie | 3             |</pre><p>departments table:</p><pre>| id | department_name |<br>|----|-----------------|<br>| 1  | HR              |<br>| 2  | Finance         |<br>| 3  | IT              |<br>| 4  | Marketing       |</pre><p>Query</p><pre>SELECT employees.name, departments.department_name<br>FROM employees<br>INNER JOIN departments<br>ON employees.department_id = departments.id;</pre><p>Result:</p><pre>| name    | department_name |<br>|---------|-----------------|<br>| Alice   | HR              |<br>| Bob     | Finance         |<br>| Charlie | IT              |</pre><p>In this example, the INNER JOIN matches the department_id in the Employees table with the id in the Departments table. Only the rows where there is a match (i.e., department.id 1, 2, and 3) are included in the result set.</p><h3>2.LEFT JOIN</h3><p>A LEFT JOIN, also referred to as a<strong> LEFT OUTER JOIN</strong>, is a type of SQL join where all rows from the left table (table1) are returned regardless of whether there is a match in the right table (table2). It includes the matching rows from the right table based on a related column specified in the ON clause of the LEFT JOIN statement.</p><p>This join condition ensures that for each row from the left table, the LEFT JOIN includes the corresponding matching rows from the right table in the result set. If there is no match found in the right table, NULL values are returned for the columns from the right table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*fYtdh0sSemUfMSBwKoXFoA.png" /><figcaption>left join</figcaption></figure><h4>Syntax of LEFT JOIN</h4><pre>SELECT columns<br>FROM table1<br>LEFT JOIN table2<br>ON table1.common_column = table2.common_column;</pre><ul><li>SELECT columns specifies the columns you want to select from the combined result set.</li><li>table1 and table2 are the names of the tables you want to join.</li><li>LEFT JOIN indicates that you&#39;re performing a left join.</li><li>ON table1.common_column = table2.common_column specifies the join condition, where common_column is the column that exists in both tables and is used to match rows between them.</li></ul><h4>Example of LEFT JOIN</h4><p>Let’s consider two example tables: Customers and Orders.</p><p>customers table:</p><pre>| id | name    | email              |<br>|----|---------|--------------------|<br>| 1  | Alice   | alice@example.com  |<br>| 2  | Bob     | bob@example.com    |<br>| 3  | Charlie | charlie@example.com|<br>| 4  | David   | david@example.com  |</pre><p>orders table:</p><pre>| id | customer_id | product    | quantity |<br>|----|-------------|------------|----------|<br>| 1  | 1           | Laptop     | 1        |<br>| 2  | 2           | Smartphone | 2        |<br>| 3  | 1           | Headphones | 1        |<br>| 4  | 3           | Tablet     | 1        |</pre><p>Query</p><pre>SELECT customers.name, orders.id AS order_id, orders.product, orders.quantity<br>FROM customers<br>LEFT JOIN orders ON customers.id = orders.customer_id;</pre><p>Result:</p><pre>| name    | order_id | product    | quantity |<br>|---------|----------|------------|----------|<br>| Alice   | 1        | Laptop     | 1        |<br>| Alice   | 3        | Headphones | 1        |<br>| Bob     | 2        | Smartphone | 2        |<br>| Charlie | 4        | Tablet     | 1        |<br>| David   | NULL     | NULL       | NULL     |</pre><p>This query retrieves the name column from the customers table and the id (renamed to order_id), product, and quantity columns from the orders table, joining them on the id column of customers and the customer_id column of orders.</p><h3>3.RIGHT JOIN</h3><p>A RIGHT JOIN, also known as <strong>RIGHT OUTER JOIN</strong>, is a type of SQL join that returns all rows from the right table (table2) and includes matching rows from the left table (table1). The join condition is based on a related column between the two tables, specified in the ON clause of the RIGHT JOIN statement.</p><p>The RIGHT JOIN ensures that all rows from the right table are retained in the result set, and for each row from the right table, it includes the corresponding matching rows from the left table based on the join condition. If there is no match found in the left table, NULL values are returned for the columns from the left table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*Ge6RpHksJTNkTVa1DEz0Gw.png" /><figcaption>right join</figcaption></figure><h4>Syntax of RIGHT JOIN</h4><pre>SELECT columns<br>FROM table1<br>RIGHT JOIN table2<br>ON table1.common_column = table2.common_column;</pre><ul><li>SELECT columns specifies the columns you want to select from the combined result set.</li><li>table1 and table2 are the names of the tables you want to join.</li><li>RIGHT JOIN indicates that you&#39;re performing a right join.</li><li>ON table1.common_column = table2.common_column specifies the join condition, where common_column is the column that exists in both tables and is used to match rows between them.</li></ul><h4>Example of RIGHT JOIN</h4><p>Let’s consider two example tables: Customers and Orders.</p><p>customers table:</p><pre>| id | name    | email              |<br>|----|---------|--------------------|<br>| 1  | Alice   | alice@example.com  |<br>| 2  | Bob     | bob@example.com    |<br>| 3  | Charlie | charlie@example.com|<br>| 4  | David   | david@example.com  |</pre><p>orders table:</p><pre>| id | customer_id | product    | quantity |<br>|----|-------------|------------|----------|<br>| 1  | 1           | Laptop     | 1        |<br>| 2  | 2           | Smartphone | 2        |<br>| 3  | 1           | Headphones | 1        |<br>| 4  | 3           | Tablet     | 1        |<br>| 5  | NULL        | Keyboard   | 1        |  -- Order with no associated customer</pre><p>Query</p><pre>SELECT customers.name, orders.id AS order_id, orders.product, orders.quantity<br>FROM customers<br>RIGHT JOIN orders ON orders.customer_id = customers.id;</pre><p>Result:</p><pre>| name    | order_id | product    | quantity |<br>|---------|----------|------------|----------|<br>| Alice   | 1        | Laptop     | 1        |<br>| Bob     | 2        | Smartphone | 2        |<br>| Alice   | 3        | Headphones | 1        |<br>| Charlie | 4        | Tablet     | 1        |<br>| NULL    | 5        | Keyboard   | 1        |  -- Order with no associated customer</pre><p>In this result, you can see that the order with order_id 5, which has no associated customer (customer_id is NULL), appears in the result set with the customer name as NULL. This demonstrates the use of RIGHT JOIN to include records from the right table (orders table in this case) even if there is no matching record in the left table (customers table).</p><h3>4.FULL JOIN</h3><p>A FULL JOIN, also known as a <strong>FULL OUTER JOIN</strong>, is a type of SQL join that returns all rows from both the left table (table1) and the right table (table2). When there is a match between the tables based on the join condition, the result set includes the matched rows from both tables. When there is no match, the result set includes NULL values for columns from the table without a match.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*HV1874AtxSvfZJ7TzB2GGA.png" /><figcaption>full join</figcaption></figure><h4>Syntax of FULL JOIN</h4><pre>SELECT columns<br>FROM table1<br>FULL JOIN table2<br>ON table1.common_column = table2.common_column;</pre><ul><li>columns specifies the columns you want to select.</li><li>table1 and table2 are the names of the tables you want to join.</li><li>FULL JOIN indicates that you&#39;re performing a full outer join.</li><li>common_column is the column that exists in both tables and is used as the join condition.</li></ul><h4>Example of FULL JOIN</h4><p>Let’s consider two example tables: customers and orders.</p><p>customers table:</p><pre>| id | name    | email              |<br>|----|---------|--------------------|<br>| 1  | Alice   | alice@example.com  |<br>| 2  | Bob     | bob@example.com    |<br>| 3  | Charlie | charlie@example.com|<br>| 4  | David   | david@example.com  |</pre><p>orders table:</p><pre>| id | customer_id | order_date | total_amount |<br>|----|-------------|------------|--------------|<br>| 1  | 3           | 2024-05-01 | 150          |<br>| 2  | 2           | 2024-05-02 | 200          |<br>| 3  | 1           | 2024-05-03 | 100          |<br>| 4  | 5           | 2024-05-04 | 80           |</pre><p>Query:</p><pre>SELECT customers.name, orders.id AS order_id, orders.order_date, orders.total_amount<br>FROM customers<br>FULL JOIN orders ON customers.id = orders.customer_id;</pre><p>Result:</p><pre>| name    | order_id | order_date | total_amount |<br>|---------|----------|------------|--------------|<br>| Alice   | 3        | 2024-05-03 | 100          |<br>| Bob     | 2        | 2024-05-02 | 200          |<br>| Charlie | 1        | 2024-05-01 | 150          |<br>| David   | NULL     | NULL       | NULL         |<br>| NULL    | 4        | 2024-05-04 | 80           |</pre><p>The FULL JOIN ensures that all rows from both tables are included in the result, with NULLs in place where there is no match.</p><h3>5.CROSS JOIN</h3><p>A CROSS JOIN is a type of SQL join that returns the Cartesian product of the two joined tables. This means that each row from the first table is combined with each row from the second table. The result set includes all possible combinations of rows from both tables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/290/1*L3tn07dmvDkyd7aKlla1gA.png" /><figcaption>cross join</figcaption></figure><h4>Example of CROSS JOIN</h4><p>Let’s consider two example tables: customers and orders.</p><p>customers table:</p><pre>| id | name    | email              |<br>|----|---------|--------------------|<br>| 1  | Alice   | alice@example.com  |<br>| 2  | Bob     | bob@example.com    |<br>| 3  | Charlie | charlie@example.com|<br>| 4  | David   | david@example.com  |</pre><p>products table:</p><pre>|id  | name       | amount       |<br>|----|------------|--------------|<br>| 1  | laptop     | 150          |<br>| 2  | mouse      | 200          |<br>| 3  | keyboard   | 100          |<br>| 4  | speaker    | 80           |</pre><p>We want to create a Cartesian product of the customers and products tables.</p><p>Query:</p><pre>SELECT customers.name AS customer_name, products.name AS product_name, products.amount<br>FROM customers<br>CROSS JOIN products;</pre><p>Result:</p><p>The CROSS JOIN will combine each row from the customers table with each row from the products table, resulting in the Cartesian product of the two tables. Here is what the result will look like:</p><pre>| customer_name | product_name | amount |<br>|---------------|--------------|--------|<br>| Alice         | laptop       | 150    |<br>| Alice         | mouse        | 200    |<br>| Alice         | keyboard     | 100    |<br>| Alice         | speaker      | 80     |<br>| Bob           | laptop       | 150    |<br>| Bob           | mouse        | 200    |<br>| Bob           | keyboard     | 100    |<br>| Bob           | speaker      | 80     |<br>| Charlie       | laptop       | 150    |<br>| Charlie       | mouse        | 200    |<br>| Charlie       | keyboard     | 100    |<br>| Charlie       | speaker      | 80     |<br>| David         | laptop       | 150    |<br>| David         | mouse        | 200    |<br>| David         | keyboard     | 100    |<br>| David         | speaker      | 80     |</pre><p>The CROSS JOIN is especially useful for generating combinations and creating test data, but it should be used with caution due to the potential size of the result set. Understanding how to use CROSS JOIN can greatly enhance your ability to work with and analyze relational data.</p><h3>6.SELF JOIN</h3><p>A SELF JOIN is a type of SQL join where a table is joined with itself. This is useful when you want to compare rows within the same table. It allows you to create relationships between rows in the same table based on certain conditions.</p><h4>Syntax of SELF JOIN</h4><pre>SELECT t1.column1, t2.column2<br>FROM table t1<br>JOIN table t2 ON t1.common_column = t2.common_column;</pre><ul><li>t1 and t2 are aliases for the same table.</li><li>common_column is the column that exists in both instances of the table and is used as the join condition.</li></ul><h4>Example of SELF JOIN</h4><p>Let’s consider an example with an employee table named employees.</p><p>employees table:</p><pre>| id | name    | manager_id |<br>|----|---------|------------|<br>| 1  | Alice   | 3          |<br>| 2  | Bob     | 3          |<br>| 3  | Charlie | NULL       |<br>| 4  | David   | 2          |</pre><p>We want to retrieve the names of employees and their respective managers.</p><p>Query:</p><pre>SELECT e1.name AS employee_name, e2.name AS manager_name<br>FROM employees e1<br>JOIN employees e2 ON e1.manager_id = e2.id;</pre><p>Result:</p><p>The table employees is joined with itself using aliases e1 and e2. The join condition is based on the manager_id column in e1 matching the employee_id column in e2, establishing a relationship between employees and their respective managers.</p><p>Here is what the result will look like:</p><pre>| employee_name | manager_name |<br>|---------------|--------------|<br>| Alice         | Charlie      |<br>| Bob           | Charlie      |<br>| David         | Bob          |</pre><p>The SELF JOIN is a powerful SQL technique that enables you to join a table with itself, allowing for comparisons and relationships between rows within the same table. Understanding how to use SELF JOIN can be beneficial in various scenarios, especially when dealing with hierarchical data or comparing records within a dataset.</p><h3>Conclusion</h3><p>Understanding SQL joins is necessary for anyone working with relational databases, as it allows for efficient data manipulation and extraction. By mastering these join techniques, you gain the ability to combine data from multiple tables, extract valuable insights, and make informed decisions based on relational data.</p><p>Whether you’re a beginner learning SQL or an experienced professional, having a solid understanding of SQL joins is a foundational skill that will serve you well in your database querying endeavors.</p><p>To further enhance your knowledge and skills in SQL, consider exploring advanced topics such as subqueries, window functions, and data modeling. Additionally, practice implementing SQL joins in real-world scenarios to reinforce your understanding and proficiency.</p><p>By continually learning and practicing SQL joins, you’ll be better equipped to handle complex data analysis tasks and contribute effectively to data-driven decision-making processes in your organization.</p><p>Happy querying!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88bab3457270" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Next.js: The Key to Modern Web Development]]></title>
            <link>https://medium.com/@johnnyJK/understanding-next-js-the-key-to-modern-web-development-b9c3a895d30d?source=rss-e496b7ee65a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9c3a895d30d</guid>
            <category><![CDATA[server-side-rendering]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[client-side-rendering]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[nextjs14]]></category>
            <dc:creator><![CDATA[John Kamau]]></dc:creator>
            <pubDate>Mon, 20 May 2024 09:06:02 GMT</pubDate>
            <atom:updated>2024-05-20T09:06:02.536Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*o36ZTcSYp51UxT5ZPy93Ag.jpeg" /><figcaption>NextJs 14</figcaption></figure><h3>Introduction to Next.js</h3><p>Next.js is an open-source web development framework built on top of React, developed and maintained by Vercel. It offers features for both server-side rendering (SSR) and static site generation (SSG), enabling developers to create performant and SEO-friendly web experiences.</p><p>As a React framework for building full-stack web applications, Next.js allows you to use React components to build user interfaces while providing additional features and optimizations. Under the hood, it abstracts and automatically configures the necessary tooling for React, such as bundling, compiling, and more.</p><h3>Key Features of Next.js</h3><h3>1. Server-Side Rendering (SSR)</h3><p>Server-Side Rendering is one of the standout features of Next.js. It allows web pages to be rendered on the server for each request, rather than in the browser. Here’s a more detailed look at SSR and its benefits:</p><ul><li><strong>How it Works:</strong> When a request is made to a Next.js application, the server generates the HTML for the requested page on-the-fly. This HTML is then sent to the client, where it can be displayed immediately, even before the JavaScript bundle is fully loaded and executed.</li><li><strong>Improved SEO:</strong> Because the content is rendered on the server and sent as a fully formed HTML document, search engines can crawl and index the page content more effectively. This leads to better search engine rankings compared to client-side rendered applications where content is rendered only after JavaScript execution.</li><li><strong>Faster Initial Load Times:</strong> By delivering pre-rendered HTML, SSR reduces the time it takes for a page to become interactive. Users see the fully rendered page almost immediately, enhancing the perceived performance of the application. This is particularly beneficial for users on slower networks or devices.</li><li><strong>Dynamic Content Handling:</strong> SSR is ideal for applications with content that changes frequently or needs to be personalized based on user data. It allows for dynamic content to be fetched and rendered on the server, ensuring that users always see the most up-to-date information.</li><li><strong>Example Use Case:</strong> Imagine an e-commerce website where product pages are constantly updated with new prices, stock levels, and user reviews. Using SSR, each product page can be rendered on the server with the latest data, providing a seamless and up-to-date shopping experience for the user.</li></ul><h3>2. Static Site Generation (SSG)</h3><p>Static Site Generation (SSG) is a powerful feature of Next.js that allows developers to generate static HTML pages at build time. Let’s go into detail on how SSG works and its advantages, along with an example use case.</p><ul><li><strong>How it Works:</strong> During the build process, Next.js generates static HTML for each page based on the React components and data fetching methods defined in the application. These static pages are then served directly from a content delivery network (CDN), providing fast and efficient content delivery to users.</li><li><strong>Incredibly Fast Page Loads:</strong> Since the HTML is pre-rendered and served from a CDN, users experience extremely fast load times. There is no need to wait for the server to process and render the page on each request, resulting in a more responsive and smooth user experience.</li><li><strong>Enhanced Security:</strong> Static sites are inherently more secure because they do not rely on a backend server to generate content for each request. This reduces the attack surface and eliminates common vulnerabilities associated with server-side processing, such as SQL injection and server-side scripting attacks.</li><li><strong>Reduced Server Costs:</strong> By serving static content from a CDN, the need for powerful server infrastructure is minimized. CDNs are optimized for delivering static assets efficiently, which can lead to significant cost savings, especially for high-traffic websites.</li><li><strong>SEO Benefits:</strong> Similar to SSR, SSG also improves SEO by providing pre-rendered HTML content that search engines can easily crawl and index. This ensures that all important content is visible to search engines right from the start.</li><li><strong>Example Use Case:</strong> Consider a blog or a documentation website that does not change frequently. With SSG, each blog post or documentation page is generated as a static HTML file during the build process. These static files can then be deployed to a CDN. Users accessing the blog or documentation site will experience near-instantaneous load times, and the site will be highly secure since there is no server processing involved for each request.</li></ul><h3><strong>3.Client-Side Rendering (CSR)</strong></h3><p>Client-Side Rendering (CSR) is another essential feature of Next.js, complementing its server-side rendering (SSR) and static site generation (SSG) capabilities. CSR allows portions of a web page to be generated and updated dynamically in the user’s browser, providing dynamic and interactive user experiences.</p><ul><li><strong>How it Works:</strong> In Client-Side Rendering, the initial HTML content is sent to the client, and then JavaScript running in the browser fetches additional data and updates the page dynamically. This approach is well-suited for parts of a web page that require frequent updates or user interactions.</li><li><strong>Dynamic Updates:</strong> CSR enables seamless updates to the user interface without needing to reload the entire page. This allows for a more fluid and interactive experience, such as real-time chat applications, live updates of data, or interactive forms.</li><li><strong>Reduced Server Load:</strong> Since the initial HTML content is sent to the client, the server’s workload is reduced compared to SSR. Only the necessary data and assets are fetched from the server, resulting in lighter server-side processing and improved scalability.</li><li><strong>Enhanced User Experience:</strong> Client-Side Rendering enables rich, interactive user experiences by allowing dynamic content updates without disrupting the overall page layout or user flow. This results in a more engaging and responsive app, leading to increased user satisfaction and retention.</li><li><strong>Example Use Case:</strong> Consider a social media feed, where users can post updates, like and comment on posts, and see real-time notifications. CSR can be used to update the feed dynamically as new posts are added or interactions occur. When a user scrolls through their feed, new posts can be fetched and displayed dynamically without reloading the entire page. Users can interact with posts, such as liking or commenting, and these interactions are reflected instantly without needing to refresh the page.</li></ul><h3>4. API Proxying</h3><p>API proxying is the ability to route API requests through the Next.js server, providing a convenient way to handle backend API calls within the same project. This feature simplifies the development process by allowing developers to create and manage both frontend and backend logic within a single codebase.</p><p><strong>How it Works:</strong> Next.js 14 allows developers to define API routes within the app directory inside the app/api directory. These API routes can handle incoming requests and execute server-side logic, such as fetching data from a database or integrating with external services. When a request is made to an API route, Next.js automatically routes it to the corresponding handler function.</p><ul><li><strong>Simplified Backend Development: </strong>With API proxying, developers can build and manage backend logic directly within the Next.js project, eliminating the need for a separate backend server. This streamlines the development process and reduces the complexity of managing multiple codebases.</li><li><strong>Integration with Frontend:</strong> API routes in Next.js seamlessly integrate with the frontend, allowing frontend components to make requests to the backend API using familiar HTTP methods like GET, POST, PUT, and DELETE. This simplifies data fetching and enables full-stack development within a single framework.</li></ul><h3>5.Automatic Code Splitting</h3><p>Automatic code splitting is a powerful feature of Next.js that enhances the performance and user experience of web applications by loading only the necessary code for each page. This approach minimizes the initial load time and reduces the overall size of the JavaScript bundles, making web applications faster and more efficient.</p><h4>How Automatic Code Splitting Works</h4><ul><li><strong>Page-Based Splitting: </strong>In Next.js, each page in the application is automatically split into its own JavaScript bundle. When a user navigates to a specific page, only the code required for that page is loaded. This reduces the amount of JavaScript that needs to be downloaded and executed initially, speeding up the load time.</li><li><strong>Dynamic Imports:</strong> Next.js supports dynamic imports, allowing developers to load JavaScript modules on demand. This means that large dependencies or components that are not needed immediately can be loaded asynchronously when required.</li><li><strong>Optimized Performance:</strong> By splitting the code into smaller chunks, Next.js ensures that the initial page load is as fast as possible. Subsequent page navigations are also faster since only the necessary code for the new page is fetched and executed.</li></ul><h4>Example Use Case</h4><p>Consider a web application with the following pages: Home, About, and Contact. Each page has its own set of components and dependencies.</p><ul><li>Home Page: Includes a large carousel component and some initial data fetches.</li><li>About Page: Contains a detailed team profile section with images.</li><li>Contact Page: Features a form and a map component.</li></ul><p>In a traditional single-page application (SPA), all the JavaScript for these pages would be bundled together. When a user visits the site, they would need to download the entire bundle, including the code for the About and Contact pages, even if they only want to see the Home page.</p><p>With automatic code splitting in Next.js:</p><ul><li>When a user visits the Home Page, only the JavaScript required for the Home page is loaded. This might include the carousel component and the initial data fetch logic.</li><li>If the user navigates to the About Page, Next.js dynamically loads the JavaScript bundle for the About page, which includes the team profile section and images.</li><li>Similarly, navigating to the Contact Page triggers the loading of the JavaScript bundle for the Contact page, including the form and map component.</li></ul><h3>6.Image Optimization</h3><p>Image optimization is a critical aspect of web performance, and Next.js provides built-in features to handle image optimization seamlessly. This functionality ensures that images are delivered in the most efficient format and size, improving load times and user experience.</p><h4>How Image Optimization Works</h4><p>Next.js introduces an &lt;Image&gt; component, which is designed to automatically optimize images used in your application. This component offers several key features:</p><ul><li><strong>Automatic Format Selection:</strong> The &lt;Image&gt; component can serve images in modern formats like WebP when supported by the browser, falling back to more widely supported formats like JPEG or PNG when necessary.</li><li><strong>Responsive Images:</strong> The component automatically generates multiple versions of an image in different sizes. The browser then selects the most appropriate size based on the user’s device and screen resolution.</li><li><strong>Lazy Loading:</strong> Images are lazily loaded by default, meaning they are only fetched when they are about to enter the viewport. This reduces the initial load time and improves performance, especially on pages with many images.</li><li><strong>Image CDN: </strong>When deploying with Vercel, images are automatically optimized and served from Vercel’s edge network, ensuring fast delivery across the globe.</li></ul><h3>Other Important Features in Next.js</h3><p>In addition to the key features that we have looked at in this article, Next.js offers a range of other powerful features that make it a highly versatile framework for building modern web applications. Here are some of them:</p><ol><li><strong>File-Based Routing:</strong> In Next.js version 14, all routes must be placed inside the app folder. Each file corresponding to a route should be named either page.js or page.tsx. Every folder within the app directory represents a path segment in the browser URL. This approach simplifies routing setup and management by leveraging the file structure within the app folder.</li><li><strong>Built-In CSS and Sass Support:</strong> Provides seamless integration of CSS and Sass files into components, enabling efficient styling and management of stylesheets. This feature enhances code organization and maintainability while supporting modern styling practices.</li><li><strong>Internationalized Routing (i18n):</strong> Facilitates the development of multilingual applications by offering built-in support for internationalization, including locale configuration and domain routing. This feature ensures that applications can reach a global audience with localized content.</li><li><strong>TypeScript Support:</strong> Offers native support for TypeScript, enabling developers to write type-safe code and leverage the benefits of static typing. TypeScript support enhances code quality, improves developer productivity, and reduces runtime errors.</li><li><strong>Middleware Support:</strong> Enables the use of middleware functions to intercept and modify requests and responses, enhancing the flexibility and extensibility of Next.js applications. Middleware can be leveraged for various tasks, including authentication, logging, and request processing.</li><li><strong>Authentication and Authorization:</strong> Next.js, along with libraries like NextAuth.js, provides comprehensive tools for implementing authentication and authorization mechanisms in applications. NextAuth.js simplifies the process of integrating authentication providers such as OAuth, JWT, and others, allowing developers to secure routes and control access to resources with ease. This ensures robust security for Next.js applications while offering flexibility and ease of implementation.</li><li><strong>Data Fetching:</strong> Offers various methods for fetching data, including getServerSideProps, getStaticProps, and useSWR. These methods enable efficient data fetching from APIs, databases, or other sources, ensuring optimal performance and flexibility in fetching and managing data for Next.js applications.</li><li><strong>Error Handling:</strong> Provides built-in error handling capabilities, allowing developers to gracefully handle errors and display custom error pages. Error handling in Next.js can be implemented at both the page level and globally using error boundaries, ensuring a smooth user experience even in the event of errors.</li><li><strong>Analytics Integration:</strong> Next.js seamlessly integrates with popular analytics platforms like Google Analytics, Mixpanel, and Segment. Developers can easily track user interactions, monitor performance, and gather valuable insights to improve their applications’ user experience and engagement.</li><li><strong>Vercel Deployment: </strong>Next.js seamlessly integrates with Vercel, allowing for easy deployment of Next.js applications. Vercel provides a powerful platform for hosting, scaling, and managing Next.js projects, offering features like automatic CI/CD, serverless functions, and global CDN distribution.</li></ol><h3>Conclusion</h3><p>Next.js is a powerful and versatile framework that simplifies the development of modern web applications. With its comprehensive features and intuitive design, it enables developers to create performant, scalable, and secure applications with ease. Whether building simple static sites or complex dynamic applications, Next.js provides the tools and flexibility needed to succeed in today’s fast-paced web development landscape.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9c3a895d30d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Hooks : A Comprehensive Beginner’s Guide]]></title>
            <link>https://medium.com/@johnnyJK/react-hooks-a-comprehensive-beginners-guide-a93a2a7d85e6?source=rss-e496b7ee65a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/a93a2a7d85e6</guid>
            <category><![CDATA[useeffect-hook]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react-hook-usereducer]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[usecallback-hook]]></category>
            <dc:creator><![CDATA[John Kamau]]></dc:creator>
            <pubDate>Wed, 06 Mar 2024 09:02:44 GMT</pubDate>
            <atom:updated>2024-03-06T09:20:47.941Z</atom:updated>
            <content:encoded><![CDATA[<h3>React Hooks : A Comprehensive Beginner’s Guide</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*jBsXkCIbVy9S_HuWOFfK7w.png" /><figcaption>react-hooks</figcaption></figure><h3>Introduction</h3><p>React is an open-source JavaScript-based user interface library, highly popular for web and mobile app development. It adheres to the principle of component-based architecture, where a component serves as an isolated and reusable piece of code. Components in React can be classified into two types: <strong>class components</strong> and <strong>functional components.</strong></p><p>Before version 16.8, React developers could only manage state and other features using class components. However, with the introduction of version 16.8, React introduced a new pattern known as Hooks. Hooks enable developers to utilize state and other React features within functional components, empowering them to apply functional programming principles in React.</p><p>Throughout this article, we will delve into the fundamentals of React Hooks, exploring core concepts such as useState, useEffect, useContext, and the art of crafting custom hooks. By the end, you&#39;ll not only grasp the syntax and usage of Hooks but also gain a deeper appreciation for their role in streamlining React development.</p><h3>Understanding React Hooks</h3><p>React Hooks are functions that enable functional components to “hook into” React features like state and life-cycle methods. They provide a more flexible and straightforward way to manage component logic, allowing developers to encapsulate behavior within functional components without using the class syntax.</p><p>Before the introduction of Hooks, managing state and side effects in React components was primarily done using class components. However, class components come with their own set of complexities, such as handling this binding, and this lead to verbose code. Hooks were introduced to fix these problems and give an easier way to handle component logic.</p><p>React Hooks offer several advantages over class components. Here are some of the key advantages:</p><ol><li>Simplified Syntax: Hooks offer cleaner and more concise code compared to class components.</li><li>Reusability: Hooks enable the creation of custom reusable logic, enhancing modularity.</li><li>Improved Readability: Co-locating logic with components improves code readability and reduces cognitive load.</li><li>No this Keyword: Hooks eliminate the need for this, reducing confusion and potential bugs.</li><li>Better Performance Optimization: Hooks enable React to optimize functional components more effectively.</li><li>Easier Testing: Functional components with Hooks are easier to test compared to class components.</li><li>Support for Functional Programming: Hooks encourage functional programming principles, leading to more predictable and maintainable code.</li></ol><h3>A Practical View</h3><p>Now that we’ve discussed the two methods for creating React components — using functions and classes — let’s start by creating a simple class component. This component will display a counter with a button to increase the count. Afterward, we’ll convert it to a functional component using hooks and observe the differences.</p><p><strong>Component without Hook: Class Component</strong></p><pre>import React, { Component } from &#39;react&#39;;<br><br>class CounterClass extends Component {<br>  constructor(props) {<br>    super(props);<br>    this.state = {<br>      count: 0<br>    };<br>    this.incrementCount = this.incrementCount.bind(this);<br>  }<br><br>  incrementCount() {<br>    this.setState(prevState =&gt; ({<br>      count: prevState.count + 1<br>    }));<br>  }<br><br>  render() {<br>    return (<br>      &lt;div&gt;<br>        &lt;h2&gt;Counter (Class Component)&lt;/h2&gt;<br>        &lt;p&gt;Count: {this.state.count}&lt;/p&gt;<br>        &lt;button onClick={this.incrementCount}&gt;Increment&lt;/button&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}<br><br>export default CounterClass;</pre><p><strong>Components with Hook:Functional Component:</strong></p><pre>import React, { useState } from &#39;react&#39;;<br><br>function CounterFunction() {<br>  const [count, setCount] = useState(0);<br><br>  const incrementCount = () =&gt; {<br>    setCount(prevCount =&gt; prevCount + 1);<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h2&gt;Counter (Function Component)&lt;/h2&gt;<br>      &lt;p&gt;Count: {count}&lt;/p&gt;<br>      &lt;button onClick={incrementCount}&gt;Increment&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default CounterFunction;</pre><blockquote>Both the class component and the functional component with Hooks achieve the same functionality — they both render a counter with a button to increment the count. You can experiment with both codes in practice.</blockquote><p>In this practical comparison, we can see how the function component with Hooks achieves the same functionality as the class component but with less boilerplate code. The Hook’s version offers a more concise and readable implementation, demonstrating the simplicity and effectiveness of React Hooks.</p><h3>Core React Hooks</h3><p>When developing React applications, understanding the core React Hooks is paramount. These hooks, including useState, useEffect, and useContext, form the foundation for managing state and side effects within functional components. Each hook serves a specific purpose, offering developers powerful tools to streamline their development workflow and create robust, efficient applications.</p><p>In this section, we will explore each of these core React Hooks in detail, diving into their syntax, usage, and practical applications.</p><h3>useState Hook</h3><p>The useState hook is a fundamental tool in React for managing state within functional components. Prior to the introduction of hooks, state management was primarily handled in class components. However, with the useState hook, functional components gain the ability to manage state in a straightforward and concise manner.</p><p>The useState hook is used by importing it from the React library. It is then invoked within the functional component, typically during initialization. The hook returns an array containing the current state value and a function to update that state.</p><pre>import React, { useState } from &quot;react&quot;;<br><br>function FormComponent() {<br>  // Declare state variables for each input field<br>  const [firstName, setFirstName] = useState(&quot;&quot;);<br>  const [lastName, setLastName] = useState(&quot;&quot;);<br>  const [email, setEmail] = useState(&quot;&quot;);<br>  const [formSubmitted, setFormSubmitted] = useState(false);<br><br>  // Event handler for form submission<br>  const handleSubmit = (e) =&gt; {<br>    e.preventDefault();<br>    // Set formSubmitted state to true<br>    setFormSubmitted(true);<br>    // Do something with the form data, e.g., submit to a server<br>    console.log(&quot;Form submitted:&quot;, { firstName, lastName, email });<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;form onSubmit={handleSubmit}&gt;<br>        &lt;div&gt;<br>          &lt;label htmlFor=&quot;firstName&quot;&gt;First Name:&lt;/label&gt;<br>          &lt;input<br>            type=&quot;text&quot;<br>            id=&quot;firstName&quot;<br>            name=&quot;firstName&quot;<br>            value={firstName}<br>            onChange={(e) =&gt; setFirstName(e.target.value)}<br>          /&gt;<br>        &lt;/div&gt;<br>        &lt;div&gt;<br>          &lt;label htmlFor=&quot;lastName&quot;&gt;Last Name:&lt;/label&gt;<br>          &lt;input<br>            type=&quot;text&quot;<br>            id=&quot;lastName&quot;<br>            name=&quot;lastName&quot;<br>            value={lastName}<br>            onChange={(e) =&gt; setLastName(e.target.value)}<br>          /&gt;<br>        &lt;/div&gt;<br>        &lt;div&gt;<br>          &lt;label htmlFor=&quot;email&quot;&gt;Email:&lt;/label&gt;<br>          &lt;input<br>            type=&quot;email&quot;<br>            id=&quot;email&quot;<br>            name=&quot;email&quot;<br>            value={email}<br>            onChange={(e) =&gt; setEmail(e.target.value)}<br>          /&gt;<br>        &lt;/div&gt;<br>        &lt;button type=&quot;submit&quot;&gt;Submit&lt;/button&gt;<br>      &lt;/form&gt;<br>      {formSubmitted &amp;&amp; (<br>        &lt;div&gt;<br>          &lt;h2&gt;Form Submitted States:&lt;/h2&gt;<br>          &lt;p&gt;First Name: {firstName}&lt;/p&gt;<br>          &lt;p&gt;Last Name: {lastName}&lt;/p&gt;<br>          &lt;p&gt;Email: {email}&lt;/p&gt;<br>        &lt;/div&gt;<br>      )}<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default FormComponent;</pre><p>In this example, the useState hook is used to manage both the state of the form input fields (firstName, lastName, and email) and the state to track the form submission status (formSubmitted). Each input field is associated with its own state variable, enabling dynamic updates through the onChange event handler. Upon form submission, the formSubmitted state is toggled to true, triggering the display of the submitted form states.</p><h3>useEffect Hook</h3><p>The useEffect hook in React allows developers to perform side effects in functional components. These side effects can include fetching data from an API, subscribing to events, updating the DOM, and more.</p><p>useEffect is called after every render of the component, and it enables React developers to encapsulate logic that needs to be executed in response to certain conditions, such as component mount, unmount, or updates to specific props or state variables. This hook takes two arguments: a function containing the side effect logic, and an optional array of dependencies that specify when the effect should be re-executed.</p><h4>useEffect with No Dependencies</h4><p>When the useEffect hook is used without specifying any dependencies, it runs after the initial render and on every subsequent re-render.</p><pre>import React, { useState, useEffect } from &quot;react&quot;;<br><br>function CounterComponent() {<br>  const [count, setCount] = useState(0);<br><br>  // Effect without dependencies: runs after initial render and on every re-render<br>  useEffect(() =&gt; {<br>    console.log(&#39;useEffect has been triggered&#39;)<br>    // Update document title with the current count<br>    document.title = `Clicked ${count} times`;<br>  });<br><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Click the button to increase count: {count}&lt;/p&gt;<br>      &lt;button onClick={() =&gt; setCount(count + 1)}&gt;Increase Count&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default CounterComponent;</pre><p>The useEffect function updates the document title with the current count value, ensuring it reflects the number of times the button has been clicked. When the button is clicked, the setCount function updates the state, triggering a re-render of the component and the execution of useEffect, which updates the document title again.</p><p>This component demonstrates the use of the useEffect hook to perform side effects (updating the document title) that should occur after every render, without depending on any specific variables or state values.</p><h4>useEffect with Empty Dependency Array</h4><p>The useEffect hook with an empty dependency array ([]) is used to perform side effects that should only occur once, after the initial render of the component. This means the effect runs only after the component mounts, and it doesn&#39;t depend on any variables or state.</p><pre>import React, { useState, useEffect } from &#39;react&#39;;<br><br>function TimerComponent() {<br>  const [timer, setTimer] = useState(0);<br><br>  useEffect(() =&gt; {<br>    // Setup subscription to a timer when compnent mounts<br>    const intervalId = setInterval(() =&gt; {<br>      setTimer(prevTimer =&gt; prevTimer + 1);<br>    }, 1000);<br><br>    // Cleanup function: Clear the subscription when component unmounts<br>    return () =&gt; {<br>      clearInterval(intervalId);<br>    };<br>  }, []);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Timer: {timer}&lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default TimerComponent;</pre><p>In this component, we utilize the useState hook to create a timer state variable for tracking elapsed time in secs. Within the useEffect hook, we establish a timer subscription using setInterval, incrementing the timer value every second. To prevent memory leaks, a cleanup function utilizing clearInterval is returned to clear the subscription upon component unmount.</p><p>With an empty dependency array ([]), the effect runs only once after the initial render, ensuring proper setup of the timer subscription. Finally, the component displays the current timer value in a paragraph element.</p><h4>useEffect With Dependencies</h4><p>When using the useEffect hook with dependencies, the effect will run after the initial render and then re-run whenever any of the dependencies change. This is useful for scenarios where you want to perform certain actions based on changes to specific variables or state values.</p><pre>import React, { useState, useEffect } from &#39;react&#39;;<br><br>function CounterComponent() {<br>  const [count, setCount] = useState(0);<br><br>  useEffect(() =&gt; {<br>    console.log(&#39;Count has changed:&#39;, count);<br>  }, [count]); // Dependency array with &#39;count&#39;<br><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Count: {count}&lt;/p&gt;<br>      &lt;button onClick={() =&gt; setCount(count + 1)}&gt;Increase Count&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default CounterComponent;</pre><p>In this component, we initialize a counter variable count using useState. The useEffect hook is configured with a dependency array [count], so it runs whenever count changes. Inside the effect, we log a message to the console indicating the change in count. Clicking the button updates count, triggering the effect again. If there were multiple dependencies specified in the array, the effect would run whenever any of them change. This allows React developers to perform actions in response to changes in specific variables or state values.</p><p>In summary, the useEffect hook in React is exclusively used within function components and custom hooks to manage side effects. It allows developers to perform actions in response to changes in variables, state, or component lifecycle events. By specifying dependencies, developers can control when the effect runs, ensuring efficient execution. Cleanup functions can also be utilized to manage resource cleanup or subscription unsubscription.</p><h3>useContext Hook</h3><p>useContext is a React hook that offers a means to share data (context) across multiple components without explicitly passing it through props, thereby addressing the issue of prop drilling. It is part of the React Context API, which is integrated into the React library.</p><p>By utilizing useContext, components can consume context values provided by a Provider higher up in the component tree, eliminating the need to pass data through intermediate components. This approach streamlines code and improves scalability.</p><p>In a typical React project, you would organize your code into different files and folders. Here’s how the project might be structured:</p><pre>src/<br>|-- components/<br>|   |-- ThemedComponent.jsx      // Contains ThemedComponent code<br>|-- contexts/<br>|   |-- ThemeContext.jsx           // Contains ThemeContext code<br>|-- App.jsx         <br>|-- main.jsx </pre><pre>//ThemedComponent.jsx<br>import React, { useContext } from &#39;react&#39;;<br>import { ThemeContext } from &#39;../contexts/ThemeContext&#39;;<br><br>const ThemedComponent = () =&gt; {<br>  const theme = useContext(ThemeContext);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Current Theme: {theme}&lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default ThemedComponent;</pre><pre>//ThemeContext.jsx<br>import React, { createContext } from &#39;react&#39;;<br><br>export const ThemeContext = createContext();<br><br>export const ThemeProvider = ({ children }) =&gt; {<br>  const theme = &#39;light&#39;; // For simplicity, hardcoding the theme here<br>  return (<br>    &lt;ThemeContext.Provider value={theme}&gt;<br>      {children}<br>    &lt;/ThemeContext.Provider&gt;<br>  );<br>};</pre><pre>//App.jsx<br>import React from &#39;react&#39;;<br>import ThemedComponent from &#39;./components/ThemedComponent&#39;;<br>import { ThemeProvider } from &#39;./contexts/ThemeContext&#39;;<br><br>const App = () =&gt; {<br>  return (<br>    &lt;ThemeProvider&gt;<br>      &lt;ThemedComponent /&gt;<br>    &lt;/ThemeProvider&gt;<br>  );<br>};<br><br>export default App;</pre><p>In the provided code, the useContext hook is used within the ThemedComponent functional component to directly consume the theme context from the ThemeContext.Provider. This approach simplifies data access by eliminating the need for prop drilling or callback functions</p><p>By utilizing useContext, the component becomes independent of the specific location where the context is defined, enhancing its reusability and maintainability. Moreover, useContext facilitates cleaner component code, as it abstracts away the complexities of context usage, leading to more comprehensible components.</p><h3>useReducer Hook</h3><p>This hook is used for managing complex state logic in a more organized and predictable way. It is especially beneficial when dealing with state objects that have multiple properties or when state transitions depend on the previous state</p><p>The useReducer hook in React takes two arguments: a reducer function and an initial state value. The reducer function specifies how the state should be updated based on the action dispatched to it, taking the current state and action as arguments and returning the new state. The initial state value represents the starting state of the component and can be a simple value, object, or array.</p><pre>import React, { useReducer } from &#39;react&#39;;<br><br>// Define the reducer function<br>const reducer = (state, action) =&gt; {<br>  switch (action.type) {<br>    case &#39;INCREMENT&#39;:<br>      return { count: state.count + 1 };<br>    case &#39;DECREMENT&#39;:<br>      return { count: state.count - 1 };<br>    default:<br>      return state;<br>  }<br>};<br><br>const Counter = () =&gt; {<br>  // Initialize state using useReducer<br>  const [state, dispatch] = useReducer(reducer, { count: 0 });<br><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Count: {state.count}&lt;/p&gt;<br>      &lt;button onClick={() =&gt; dispatch({ type: &#39;INCREMENT&#39; })}&gt;Increment&lt;/button&gt;<br>      &lt;button onClick={() =&gt; dispatch({ type: &#39;DECREMENT&#39; })}&gt;Decrement&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default Counter;</pre><p>In this example, we utilize the useReducer hook to manage state in a React component. We start by defining a reducer function that handles state updates based on dispatched actions. Next, we initialize the state using useReducer, passing the reducer function and initial state as arguments. This hook returns an array containing the current state and a dispatch function.</p><p>Within the component, we render the current count value from the state object and two buttons that dispatch INCREMENT and DECREMENT actions. When an action is dispatched, the reducer function updates the state accordingly, triggering a re-render of the component with the updated state.</p><h3>useCallback Hook</h3><p>useCallback hook in React is used to memoize functions, optimizing performance by preventing unnecessary re-renders caused by function recreations. When a function is wrapped with useCallback, React will return the same memoized function reference on subsequent renders as long as the dependencies listed in the dependency array remain unchanged.</p><p>The useCallback hook takes two arguments: the callback function and an array of dependencies. If any of the dependencies in the array change, the callback function is re-created; otherwise, the cached version of the function is returned.</p><pre>import React, { useState, useCallback } from &#39;react&#39;;<br><br>//CounterButton.jsx<br>const CounterButton = ({ onClick }) =&gt; {<br>  console.log(&#39;Rendering CounterButton&#39;);<br>  return &lt;button onClick={onClick}&gt;Click Me!&lt;/button&gt;;<br>};<br><br>//App.jsx<br>const App = () =&gt; {<br>  const [count, setCount] = useState(0);<br><br>  // Define a memoized callback function using useCallback<br>  const handleClick = useCallback(() =&gt; {<br>    setCount(prevCount =&gt; prevCount + 1);<br>  }, []); // No dependencies, the function is created only once<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Counter: {count}&lt;/h1&gt;<br>      &lt;CounterButton onClick={handleClick} /&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default App;</pre><p>In this example, we utilize the useCallback hook to create a memoized callback function named handleClick. This function increments the count state by 1 when invoked. By specifying an empty dependency array [], we ensure that handleClick is memoized and created only once, returning the same function reference on subsequent renders. This optimization prevents unnecessary re-renders of the CounterButton component, as it no longer reacts to changes in the handleClick function reference. As a result, the application&#39;s performance is improved by avoiding unnecessary component re-renders.</p><h3>useMemo hook</h3><p>useMemo hook in React is used to memoize the result of a computation, optimizing performance by caching expensive calculations and returning the cached value when the dependencies remain unchanged.</p><p>It takes a function as its first argument, which computes the value to be memoized, and an array of dependencies as its second argument. When any of the dependencies change, the memoized value is recalculated.</p><pre>import React, { useState, useMemo } from &#39;react&#39;;<br><br>const fibonacci = n =&gt; {<br>  if (n &lt;= 1) return n;<br>  return fibonacci(n - 1) + fibonacci(n - 2);<br>};<br><br>const App = () =&gt; {<br>  const [number, setNumber] = useState(20);<br>  const [otherState, setOtherState] = useState(false);<br><br>  // Memoize the result of the fibonacci calculation<br>  const fibResult = useMemo(() =&gt; fibonacci(number), [number]);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Calculate Fibonacci Number&lt;/h1&gt;<br>      &lt;p&gt;Number: {number}&lt;/p&gt;<br>      &lt;p&gt;Fibonacci Result: {fibResult}&lt;/p&gt;<br>      &lt;p&gt;Other State: {otherState.toString()}&lt;/p&gt;<br>      &lt;button onClick={() =&gt; setNumber(prevNumber =&gt; prevNumber + 1)}&gt;<br>        Increment Number<br>      &lt;/button&gt;<br>      &lt;button onClick={() =&gt; setOtherState(prevState =&gt; !prevState)}&gt;<br>        Toggle State<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default App;</pre><p>In this example, we utilize the useMemo hook to optimize the performance of a Fibonacci calculation within a React functional component. The component manages a number state representing the input to the Fibonacci calculation using the useState hook. By employing useMemo, we memoize the result of the Fibonacci calculation based on the number state. This ensures that the expensive computation is only performed when the number state changes, preventing unnecessary recalculations during component re-renders.</p><p>When we click on the “Toggle State” button, the App component re-renders due to the state update of otherState. However, despite the component re-rendering, the Fibonacci calculation is not recomputed unnecessarily. This is because useMemo memoizes the result of the Fibonacci calculation based on the number state, which remains unchanged when toggling otherState.</p><h3>useRef Hook</h3><p>useRef hook in React is used to create a mutable reference that persists across re-renders of the component. Unlike useState, changes to a useRef value do not trigger a re-render of the component. useRef is commonly used to access and interact with DOM elements or to persist values across renders without triggering re-renders.</p><pre>import React, { useRef } from &#39;react&#39;;<br><br>const App = () =&gt; {<br>  const inputRef = useRef(null);<br><br>  const handleFocus = () =&gt; {<br>    inputRef.current.focus();<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;input ref={inputRef} type=&quot;text&quot; /&gt;<br>      &lt;button onClick={handleFocus}&gt;Focus Input&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default App;</pre><p>In this example, we utilize the useRef hook to create a reference named inputRef, which is then assigned to the ref attribute of an input element. When the &quot;Focus Input&quot; button is clicked, invoking the handleFocus function, the input element gains focus via inputRef.current.focus(). Despite this focus action, the component does not re-render because useRef does not trigger re-renders.</p><h3>Other React Hooks</h3><p><strong>useLayoutEffect Hook: </strong>is similar to useEffect, but it’s executed synchronously after all DOM mutations have been applied but before the browser paints the changes on the screen. This makes it suitable for tasks that require measurements or DOM manipulations and need to be performed before the user sees the updates.</p><p><strong>useDebugValue hook:</strong> is a React hook that is used to provide additional debug information about custom hooks in React DevTools. It allows you to display custom labels and values for custom hooks in the React DevTools inspector, making it easier to debug and understand how custom hooks are being used in your application.</p><p><strong>useImperativeHandle hook: </strong>is used to customize the instance value that is exposed by a parent component when using the forwardRef feature in React. It allows child components to expose specific methods or properties to their parent components, providing a way to interact with the child component&#39;s instance from its parent.</p><h3><strong>Custom Hooks</strong></h3><p>Custom hooks in React are JavaScript functions that utilize one or more built-in React hooks to encapsulate and share reusable logic across components. They allow developers to abstract complex logic into reusable pieces, promoting code reusability and composability.</p><p>They must follow a naming convention where their names start with the prefix “use”. This convention is enforced by React’s ESLint rules to help developers distinguish between regular functions and custom hooks.</p><p>Let’s create a useFetch custom hook that enables us to fetch data from a specified URL and handle loading states and errors.</p><pre>import { useState, useEffect } from &#39;react&#39;;<br><br>function useFetch(url) {<br>  const [data, setData] = useState(null);<br>  const [loading, setLoading] = useState(true);<br>  const [error, setError] = useState(null);<br><br>  useEffect(() =&gt; {<br>    const fetchData = async () =&gt; {<br>      try {<br>        const response = await fetch(url);<br>        if (!response.ok) {<br>          throw new Error(&#39;Failed to fetch data&#39;);<br>        }<br>        const jsonData = await response.json();<br>        setData(jsonData);<br>        setLoading(false);<br>      } catch (error) {<br>        setError(error);<br>        setLoading(false);<br>      }<br>    };<br><br>    fetchData();<br>  }, [url]);<br><br>  return { data, loading, error };<br>}<br><br>export default useFetch;</pre><p>This custom hook useFetch takes a URL as its parameter and returns an object containing the fetched data (data), a boolean flag indicating whether the data is still loading (loading), and any error that may occur during the fetch (error).</p><p>You can use this custom hook in your components like this:</p><pre>import React from &#39;react&#39;;<br>import useFetch from &#39;./useFetch&#39;;<br><br>function MyComponent() {<br>  const { data, loading, error } = useFetch(&#39;https://api.example.com/data&#39;);<br><br>  if (loading) {<br>    return &lt;p&gt;Loading...&lt;/p&gt;;<br>  }<br><br>  if (error) {<br>    return &lt;p&gt;Error: {error.message}&lt;/p&gt;;<br>  }<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Data:&lt;/h1&gt;<br>      &lt;pre&gt;{JSON.stringify(data, null, 2)}&lt;/pre&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default MyComponent;</pre><p>With this custom hook, you can easily fetch data from any API endpoint in your React components while handling loading states and errors in a clean and reusable manner.</p><h3>Summary</h3><p>React hooks have ushered in a new era of efficiency and effectiveness in web development. With hooks like useReducer for state management and useMemo and useCallback for performance optimization, developers can unlock new levels of productivity and innovation.</p><p>They are not limited to experts; developers of all skill levels can leverage these tools. Whether you’re a seasoned professional or new to React, integrating these hooks into your projects can simplify code, improve performance, and elevate user experiences.</p><p>In summary, React hooks are indispensable for React developers aiming to build faster and more responsive web applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a93a2a7d85e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Axios vs. Fetch API: Selecting the Right Tool for HTTP Requests]]></title>
            <link>https://medium.com/@johnnyJK/axios-vs-fetch-api-selecting-the-right-tool-for-http-requests-ecb14e39e285?source=rss-e496b7ee65a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/ecb14e39e285</guid>
            <category><![CDATA[http-client]]></category>
            <category><![CDATA[fetch-api]]></category>
            <category><![CDATA[axios-vs-fetch]]></category>
            <category><![CDATA[axios]]></category>
            <category><![CDATA[http-request]]></category>
            <dc:creator><![CDATA[John Kamau]]></dc:creator>
            <pubDate>Thu, 22 Feb 2024 10:09:13 GMT</pubDate>
            <atom:updated>2024-02-22T10:09:13.552Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*quTpcb5i1NuOx235KQynOg.jpeg" /></figure><p>In the field of software development, the ability to seamlessly interact with remote servers and exchange data over the web is very important. Whether it’s fetching data from an API, performing CRUD operations, or executing any other network-related task, the significance of making HTTP requests cannot be overstated. Two widely used JavaScript libraries, Fetch and Axios, have become top picks for developers seeking to handle HTTP requests.</p><p>In this article, we will compare Axios and Fetch to see how they can be used to perform different tasks. Hopefully, by the end of the article, you’ll have a better understanding of both APIs.</p><h3>AXIOS</h3><p>Axios is a third-party HTTP client library for making network requests. It is promise-based and provides a clean and consistent API for handling requests and responses.</p><p>You can add it to your project via a content distribution network (CDN) or by using a package manager (like <a href="https://www.npmjs.com/">npm</a>). Some of its core features include: making <a href="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest">XMLHttpRequests</a> within a browser, making http requests within a node.js environment, canceling requests, and intercepting request and response.</p><h3>FETCH</h3><p>Fetch, like Axios, is a promise-based HTTP client. It is a built-in API; hence we don’t have to install or import anything. It’s available in all modern browsers; you can check it on <a href="https://caniuse.com/fetch">caniuse</a>. Fetch is also available in node.js — you can read more about it <a href="https://github.com/nodejs/node/pull/41749">here</a>.</p><p>Let’s now compare their basic syntax, features, and use cases as we try to understand the two popularly used libraries.</p><h3>Basic Syntax</h3><p>Axios simplifies HTTP requests with a chainable API which allows for straightforward configuration of request parameters, such as headers, data, and request method.</p><p>Here’s how to use Axios to send a [POST] request with custom headers to a URL. Axios automatically converts the data to JSON, so you don’t have to.</p><pre>const axios = require(&#39;axios&#39;);<br><br>const url = &#39;https://jsonplaceholder.typicode.com/posts&#39;;<br>const data = {<br>  title: &#39;Hello World&#39;,<br>  body: &#39;This is a test post.&#39;,<br>  userId: 1,<br>};<br><br>axios<br>  .post(url, data, {<br>    headers: {<br>      Accept: &#39;application/json&#39;,<br>      &#39;Content-Type&#39;: &#39;application/json;charset=UTF-8&#39;,<br>    },<br>  })<br>  .then(({ data }) =&gt; {<br>    console.log(&quot;POST request successful. Response:&quot;, data);<br>  })<br>  .catch(error =&gt; {<br>    console.error(&#39;Error:&#39;, error);<br>  });</pre><p>Compare that code to the fetch API code, which produces the exact same result:</p><pre>const url = &quot;https://jsonplaceholder.typicode.com/todos&quot;;<br><br>const options = {<br>  method: &quot;POST&quot;,<br>  headers: {<br>    Accept: &quot;application/json&quot;,<br>    &quot;Content-Type&quot;: &quot;application/json;charset=UTF-8&quot;,<br>  },<br>  body: JSON.stringify({<br>    title: &quot;Hello World&quot;,<br>    body: &quot;This is a test post.&quot;,<br>    userId: 1,<br>  }),<br>};<br><br>fetch(url, options)<br>  .then((response) =&gt; response.json())<br>  .then((data) =&gt; {<br>    console.log(&quot;POST request successful. Response:&quot;, data);<br>  });</pre><p>Fetch uses the body property for sending data in a POST request, whereas Axios utilizes the data property. Axios will automatically transforms the server’s response data, while with Fetch, you need to call the response.json method to parse the data into a JavaScript object. Furthermore, Axios delivers the data response within the data object, whereas Fetch allows the final data to be stored in any variable.</p><h3><strong>Handling Response and Errors</strong></h3><p>Fetch offers precise control over the loading process but introduces complexity by requiring the handling of two promises. Additionally, when dealing with responses, Fetch requires parsing JSON data using the .json() method. The final data retrieved can then be stored in any variable.</p><p>For HTTP response errors, Fetch does not automatically throw an error. Instead, it considers the response as successful even if the server returns an error status code (e.g., 404 Not found).</p><p>To handle HTTP errors explicitly in Fetch, developers have to use conditional statements within the .then() block to check the response.ok property. If response.ok is false, it indicates that the server responded with an error status code, and developers can handle the error accordingly.</p><p>Here is a [GET] request using fetch:</p><pre>fetch(&#39;https://jsonplaceholder.typicode.com/todos&#39;)<br>  .then(response =&gt; {<br>    if (!response.ok) {<br>      throw Error(`HTTP error: ${response.status}`);<br>    }<br>    return response.json();<br>  })<br>  .then(data =&gt; {<br>    console.log(&#39;Data received:&#39;, data);<br>  })<br>  .catch(error =&gt; {<br>    console.error(&#39;Error message:&#39;, error.message);<br>  });</pre><p>Axios, on the other hand, simplifies response handling by directly providing access to the data property. It automatically rejects responses outside of the 200–299 range (successful responses). By utilizing a .catch() block, information about the error can be obtained, including whether a response was received and, if so, its status code. This contrasts with fetch, where unsuccessful responses are still resolved.</p><p>Here is a [GET] request using Axios:</p><pre>const axios = require(&quot;axios&quot;);<br><br>axios<br>  .get(&quot;https://jsonplaceholder.typicode.com/todos&quot;)<br>  .then((response) =&gt; {<br>    console.log(&quot;Data received:&quot;, response.data);<br>  })<br>  .catch((error) =&gt; {<br>    if (error.response) {<br>      console.error(`HTTP error: ${error.response.status}`);<br>    } else if (error.request) {<br>      console.error(&quot;Request error: No response received&quot;);<br>    } else {<br>      console.error(&quot;Error:&quot;, error.message);<br>    }<br>  });</pre><p>By automatically throwing errors for unsuccessful responses, Axios simplifies error handling and allows developers to focus on implementing appropriate error-handling logic without having to manually check each response for success or failure.</p><h3><strong>Intercepting HTTP Requests and Responses</strong></h3><p>One of the key features of Axios is its ability to intercept HTTP requests. HTTP interceptors come in handy when you need to examine or change HTTP requests from your application to the server or vice versa. This functionality is essential for various tasks such as logging, authentication, or retrying failed HTTP requests.</p><p>With interceptors, you won’t have to write separate code for each HTTP request. HTTP interceptors are helpful when you want to set a global strategy for how you handle requests and responses.</p><p>Here is how to intercept an HTTP request using Axios:</p><pre>const axios = require(&quot;axios&quot;);<br><br>// Register a request interceptor<br>axios.interceptors.request.use((config) =&gt; {<br>  // Log a message before any HTTP request is sent<br>  console.log(&quot;Request was sent&quot;);<br>  return config;<br>});<br><br>// Send a GET request<br>axios<br>  .get(&quot;https://jsonplaceholder.typicode.com/todos&quot;)<br>  .then(({data}) =&gt; {<br>    console.log(&quot;Data received:&quot;, data);<br>  })<br>  .catch((error) =&gt; {<br>    console.error(&quot;Error:&quot;, error.message);<br>  });</pre><p>In this code, the axios.interceptors.request.use() method is used to define code to run before an HTTP request is sent.</p><p>Additionally, axios.interceptors.request.use() can be employed to intercept the response from the server. For instance, in the event of a network error, response interceptors can be utilized to retry the same request using interceptors.</p><p>By default, fetch() doesn’t provide a way to intercept requests, but it’s not hard to come up with a workaround. You can overwrite the global fetch() method and define your interceptor, like this:</p><p>Here is how to intercept an HTTP request using Fetch:</p><pre>fetch = ((originalFetch) =&gt; {<br>  return (...arguments) =&gt; {<br>    return originalFetch.apply(this, arguments).then((response) =&gt; {<br>      if (!response.ok) {<br>        throw new Error(`HTTP error: ${response.status}`);<br>      }<br>      console.log(&quot;Request was sent&quot;);<br>      return response;<br>    });<br>  };<br>})(fetch);<br><br>fetch(&quot;https://jsonplaceholder.typicode.com/todos&quot;)<br>  .then((response) =&gt; response.json())<br>  .then((data) =&gt; {<br>    console.log(&quot;Data received:&quot;, data);<br>  })<br>  .catch((error) =&gt; {<br>    console.error(&quot;Error:&quot;, error.message);<br>  });</pre><p>Fetch tends to have more boilerplate code compared to Axios. However, the choice should be based on the use case and individual needs.</p><h3><strong>Response Timeout</strong></h3><p>Response timeout is indeed another important area for comparison between Fetch and Axios. Response timeout refers to the duration for which a client will wait for a response from the server before considering the request as failed.</p><p>The simplicity of setting a timeout in Axios is one of the reasons some developers prefer it to Fetch. In Axios, you can use the optional timeout property in the config object to set the number of milliseconds before the request is aborted. This straightforward approach allows developers to define the timeout duration directly within the request configuration, providing greater control and ease of implementation.</p><p>Here is a [GET] request with a specified timeout using Axios:</p><pre>const axios = require(&#39;axios&#39;);<br><br>// Define the timeout duration in milliseconds<br>const timeout = 5000; // 5 seconds<br><br>// Create a config object with the timeout property<br>const config = {<br>  timeout: timeout<br>};<br><br>// Send a GET request with the specified timeout<br>axios.get(&#39;https://jsonplaceholder.typicode.com/todos&#39;, config)<br>  .then(response =&gt; {<br>    console.log(&#39;Data received:&#39;, response.data);<br>  })<br>  .catch(error =&gt; {<br>    console.error(&#39;Error fetching data:&#39;, error.message);<br>  });</pre><p>A GET request is being sent using Axios, passing the config object as the second argument to specify the timeout. If the request is successful, the received data is logged to the console. If an error occurs during the request or if the timeout is reached, the error message is logged to the console.</p><p>Fetch offers similar functionality through the AbortController interface, although it’s not as straightforward as the Axios version.</p><p>Here is how to intercept an HTTP request using Fetch:</p><pre>const timeout = 5000; // 5 seconds<br>// Create an AbortController instance<br>const controller = new AbortController();<br>const signal = controller.signal;<br><br>// Set up a setTimeout function to abort the fetch request after the specified timeout<br>const timeoutId = setTimeout(() =&gt; {<br>  controller.abort();<br>}, timeout);<br><br>// Make the fetch request with the specified URL and signal<br>fetch(&#39;https://jsonplaceholder.typicode.com/todos&#39;, { signal })<br>  .then(response =&gt; {<br>    if (!response.ok) {<br>      throw new Error(&#39;Network response was not ok&#39;);<br>    }<br>    return response.json();<br>  })<br>  .then(data =&gt; {<br>    console.log(&#39;Data received:&#39;, data);<br>  })<br>  .catch(error =&gt; {<br>    // Check if the error is due to the request being aborted<br>    if (error.name === &#39;AbortError&#39;) {<br>      console.error(&#39;Request timed out&#39;);<br>    } else {<br>      console.error(&#39;Error fetching data:&#39;, error.message);<br>    }<br>  })<br>  .finally(() =&gt; {<br>    // Clear the timeout to prevent it from firing after the request has completed<br>    clearTimeout(timeoutId);<br>  });<br><br></pre><p>A 5-second timeout is set for the fetch request, and an AbortController is created to cancel it if it exceeds this limit. Using setTimeout, a timer is initiated to abort the request after this duration. Then, the fetch request is sent, including the abort signal. Upon response, it checks for success and parses the data. Any errors, such as timeouts, are managed accordingly. Finally, the timeout is cleared to avoid unnecessary delays after the request finished.</p><h3><strong>Simultaneous requests</strong></h3><p>Simultaneous requests, or the ability to make multiple requests concurrently, is another crucial aspect for comparison between Fetch and Axios. This feature is particularly important in applications where performance and responsiveness are paramount.</p><p>To make multiple simultaneous requests, Axios provides the <br>axios.all() method. Simply pass an array of requests to this method, then use axios.spread()to spread the responses into separate arguments. This allows handling of each response individually.</p><p>Here is how to send simultaneous HTTP requests using Axios:</p><pre>const axios = require(&#39;axios&#39;);<br><br>// Define the base URL for the request<br>const baseURL = &#39;https://jsonplaceholder.typicode.com/todos&#39;;<br><br>// Define the URLs for the requests<br>const urls = [<br>  `${baseURL}/1`,<br>  `${baseURL}/2`,<br>  `${baseURL}/3`<br>];<br><br>// Create an array of Axios request promises<br>const axiosRequests = urls.map(url =&gt; axios.get(url));<br><br>// Send multiple requests simultaneously using `axios.all()`<br>axios.all(axiosRequests)<br>  .then(axios.spread((...responses) =&gt; {<br>    // Handle responses from all requests<br>    responses.forEach((response, index) =&gt; {<br>      console.log(`Response from ${urls[index]}:`, response.data);<br>    });<br>  }))<br>  .catch(error =&gt; {<br>    console.error(&#39;Error fetching data:&#39;, error.message);<br>  });</pre><p>To achieve the same result using Fetch we have to rely on the built-in Promise.all()method. Pass all fetch requests as an array to Promise.all(). Next, handle the response by using an async function.</p><p>Here is how to send simultaneous HTTP requests using Fetch:</p><pre>// Define the base URL for the requests<br>const baseURL = &quot;https://jsonplaceholder.typicode.com/todos&quot;;<br><br>// Define the URLs for the requests<br>const urls = [`${baseURL}/1`, `${baseURL}/2`, `${baseURL}/3`];<br><br>// Create an array to store the fetch request promises<br>const fetchRequests = urls.map((url) =&gt; fetch(url));<br><br>// Send multiple requests simultaneously using `Promise.all()`<br>Promise.all(fetchRequests)<br>  .then((responses) =&gt; {<br>    // Handle responses from all requests<br>    responses.forEach((response, index) =&gt; {<br>      if (!response.ok) {<br>        throw new Error(<br>          `Request ${urls[index]} failed with status ${response.status}`<br>        );<br>      }<br>      response.json().then((data) =&gt; {<br>        console.log(`Response from ${urls[index]}:`, data);<br>      });<br>    });<br>  })<br>  .catch((error) =&gt; {<br>    console.error(&quot;Error fetching data:&quot;, error.message);<br>  });</pre><p>While this approach is feasible, it may introduce additional complexity and overhead, especially for developers unfamiliar with asynchronous programming concepts.</p><h3><strong>Backward compatibility</strong></h3><p>Backward compatibility is the ability of a software system or product to function correctly or effectively even when used with older versions of dependencies or in older environments.</p><p>Axios provides better backward compatibility out of the box and offers additional features that can facilitate compatibility with older systems or codebases. One of the main selling points of Axios is its extensive browser support, making it compatible even with older browsers like IE11 due to its underlying use of XMLHttpRequest.</p><p>In comparison, Fetch has more limited browser support, catering primarily to modern browsers such as Chrome, Firefox, Edge, and Safari. For projects requiring Fetch’s functionality in unsupported browsers, integrating a polyfill like ‘whatwg-fetch’ can bridge the gap. This polyfill extends Fetch support to older browsers, ensuring compatibility.</p><p>To use it, install it via the npm command like so:</p><pre>npm install whatwg-fetch - save</pre><p>Then, you can make requests like this:</p><pre>import &#39;whatwg-fetch&#39;<br><br>window.fetch(…)</pre><p>Keep in mind that you might also need a promise polyfill in some old browsers.</p><h3><strong>Conclusion</strong></h3><p>Axios stands out for its simplicity, robustness, and extensive browser support, making it an ideal choice for projects requiring backward compatibility with older browsers. On the other hand, Fetch offers a more native approach, built directly into the browser, with support for features like streaming and the ability to work with other web platform APIs seamlessly.</p><p>When making a decision between Axios and Fetch, developers should carefully evaluate their project requirements, including factors such as ease of use, performance considerations, browser compatibility and additional features needed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ecb14e39e285" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Navigating the Path to Success: Our Portfolio Project at ALX School]]></title>
            <link>https://medium.com/@johnnyJK/navigating-the-path-to-success-our-portfolio-project-at-alx-school-30dadb0f7b5a?source=rss-e496b7ee65a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/30dadb0f7b5a</guid>
            <category><![CDATA[holberton-school]]></category>
            <category><![CDATA[alxafrica]]></category>
            <category><![CDATA[mern-stack]]></category>
            <category><![CDATA[do-hard-things]]></category>
            <category><![CDATA[portfolio-project]]></category>
            <dc:creator><![CDATA[John Kamau]]></dc:creator>
            <pubDate>Wed, 13 Dec 2023 07:49:45 GMT</pubDate>
            <atom:updated>2023-12-13T08:14:16.976Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*vMJJCmqi2DTdaNkf77xmIg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jaesKpiTR-0bFxDz11Lwbg.png" /></figure><h3>Project Overview</h3><p>Our portfolio project at ALX School, JobHub Connect, is a dynamic job listing board designed to streamline the job application process. With an intuitive interface and robust functionalities, our application caters to both job seekers and employers. The team behind this venture comprises John Kamau (myself) and Patrick Macharia. Each of us played a pivotal role in bringing this project to life, with a collective focus on creating a seamless user experience.</p><p>JobHub Connect, aims to make job hunting easier for candidates and simplify the hiring process for employers. Job seekers can easily browse through job listings, apply for positions, and keep track of their applications. Employers benefit from a user-friendly dashboard for managing job postings, applications, and candidate profiles. The ultimate goal is to create an efficient and transparent job market experience for everyone involved.</p><h3><strong>Project Inspiration</strong></h3><p>My decision to create JobHub Connect stems from personal experiences during a challenging job search a few months ago. The process was cumbersome, and I often felt overwhelmed by the sheer volume of job listings and the manual effort required to apply. The overwhelming process inspired me to develop a platform that simplifies job hunting for both candidates and employers. JobHub Connect is not just a technical project; it’s a meaningful effort to enhance the job market experience based on real-life struggles. Our goal is to provide a user-friendly solution that resonates with individuals navigating the job market, offering them a smoother journey towards employment.</p><h3>Accomplishments</h3><p>Our project, JobHub Connect, has achieved a streamlined job application process for both job seekers and employers. The architecture diagram illustrates the smooth flow of data through the application. We chose React with MUI, Formik, and Yup for the frontend, providing an intuitive and responsive user interface. Express.js, JWT, and Bcrypt secure the backend, ensuring data integrity and user authentication. MongoDB serves as our database for efficient data storage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pFBHxPFdBqcC62Zj9sF8pw.png" /></figure><h3>Features:-</h3><ul><li><strong>Authentication and Authorization:</strong> Implemented secure user authentication and authorization using JSON Web Tokens (JWT) and cookies to ensure a robust and safe user experience.</li><li><strong>Mobile Responsiveness:</strong> Designed the frontend with a responsive layout using React with MUI, ensuring a seamless experience for users accessing the platform from various devices.</li><li><strong>Intuitive Job Listing Board:</strong> Created a user-friendly job listing board, allowing job seekers to easily browse through available positions, apply for jobs, and track their applications.</li><li><strong>Employer Dashboard:</strong> Developed a comprehensive dashboard for employers, providing a centralized platform for managing job postings.</li><li><strong>Express.js Backend:</strong> Utilized Express.js for the backend, enhancing the efficiency of data handling and ensuring a smooth interaction between the frontend and database.</li><li><strong>Data Security:</strong> Implemented Bcrypt for password hashing, adding an extra layer of security to protect user data stored in the MongoDB database.</li><li><strong>Efficient Data Storage: </strong>Utilized MongoDB as the database to efficiently store and retrieve data related to job listings, user profiles, and applications.</li><li><strong>Search and Filter Functionality:</strong> Incorporated search and filter functionalities, enabling users to find specific job listings based on criteria such as location, job type, or salary.</li></ul><h3>Technical Challenges</h3><p>During the development of JobHub Connect, implementing a secure login system with JSON Web Tokens (JWT) and cookies presented a key technical challenge. Integrating JWT-based authentication seamlessly between the frontend and backend required careful consideration for robust data security and user privacy. The complexity lay in ensuring a secure and efficient authentication flow, ultimately leading to a successful solution that enhances the platform’s overall reliability and security.</p><h4>Solution</h4><p>I tackled the challenge of integrating JWT-based authentication in JobHub Connect by carefully understanding the JWT flow and establishing a standardized communication protocol between the frontend and backend. This involved thorough error handling and validation checks to ensure secure transmission and validation of JWT tokens. By following best practices and utilizing reliable libraries for JWT handling, I successfully implemented a strong and secure authentication mechanism. This solution not only addressed the initial challenge but also improved the overall reliability and security of user authentication in JobHub Connect.</p><h3>Lessons learned</h3><p>Throughout the development of JobHub Connect, I gained valuable insights into several technical aspects and engineering practices. The implementation of user authentication using JWT and cookies enhanced my understanding of secure authentication mechanisms. I learned the importance of error handling and validation checks in ensuring the reliability and security of data transmission. Additionally, working on a full-stack project reinforced the significance of a well-structured and modular codebase for scalability and maintenance.</p><p>Reflecting on the project, I realize the importance of early planning and setting realistic timelines. Clear communication and collaboration within the team played a crucial role in overcoming challenges efficiently. This experience has highlighted the need for continuous learning and adaptation in the ever-evolving field of software engineering.</p><p>As an engineer, I discovered the satisfaction of solving complex problems and the joy of creating a tangible solution that improves user experiences. This project has solidified my passion for building practical and user-centric applications. Looking ahead, I plan to further explore advanced topics in web development and deepen my expertise in areas such as security and system architecture.</p><p>One notable takeaway is the recognition that embracing challenges and learning from setbacks is an inherent part of the engineering journey. This project has encouraged me to approach future endeavors with a resilient mindset and a commitment to continuous improvement</p><h3>Conclusion</h3><p>As a software engineer, I am passionate about crafting innovative solutions that address real-world challenges. My journey with JobHub Connect reflects my dedication to creating user-centric applications and refining my technical skills. With a strong foundation in web development and a commitment to lifelong learning, I am eager to contribute to impactful projects that push the boundaries of technology. Explore the GitHub repository for <a href="https://github.com/JohnKamaujk/JobHub_Connect">JobHub_Connect</a>, experience the deployed project <a href="https://jobhub-connect-app.onrender.com/">JobHub Connect</a>, and connect with me on LinkedIn <a href="https://www.linkedin.com/in/john-kamau-000676231">JohnK</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30dadb0f7b5a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Happens When You Type ‘www.google.com' in Your Browser and Press Enter?]]></title>
            <link>https://medium.com/@johnnyJK/what-happens-when-you-type-www-google-com-in-your-browser-and-press-enter-3ee2343d8c21?source=rss-e496b7ee65a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ee2343d8c21</guid>
            <category><![CDATA[internet]]></category>
            <category><![CDATA[firewall]]></category>
            <category><![CDATA[https]]></category>
            <category><![CDATA[load-balancer]]></category>
            <category><![CDATA[dns]]></category>
            <dc:creator><![CDATA[John Kamau]]></dc:creator>
            <pubDate>Wed, 11 Oct 2023 18:22:38 GMT</pubDate>
            <atom:updated>2023-10-11T18:29:18.325Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cpMgsRJPGCU0PcnIZ5xnBQ.jpeg" /></figure><p>In the vast realm of the internet, one URL stands out as the most universally recognized and visited: “<a href="https://www.google.com/">https://www.google.com</a>.&quot; We’ve all done it — that moment when we type those characters into our browser’s address bar and eagerly press “Enter.” But have you ever stopped to wonder what unfolds in the digital realm immediately after that click? What intricate processes are set into motion to generate the familiar list of search results that Google displays with astonishing speed?</p><p>If you’ve ever been curious about this, you’re in the right place. Instead of just scratching the surface, we’re about to dive deep into the heart of the matter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*C5eLyjPKVybGcucrOfk2jg.gif" /></figure><p>Now, before we embark on this enlightening journey through the inner workings of the internet, let’s make sure we’re on the same page. You probably know what a web browser is, but if you don’t, that’s perfectly fine. A web browser is just the application you use to explore the vast world of the internet — think Chrome, Firefox, Safari, Edge, and the like.</p><p>In this article, we will explore fundamental concepts such as URL, DNS, TCP/IP, Firewall, Load Balancer, Webservers, Application Servers, and Database</p><h3>A brief explanation of what happens when you type a URL into a web browser</h3><p>When you type a web address like “<a href="https://www.google.com/">https://www.google.com</a>&quot; into your browser and press Enter, a lot of stuff happens very quickly before you see the webpage. It all happens so fast that you might not even notice. Before we dive into the nitty-gritty details, let me give you a quick summary of what takes place in that split second.</p><ol><li><strong>Domain Name System (DNS) Request:</strong> Your computer asks a DNS server to find the IP address linked to “<a href="https://www.google.com/">https://www.google.com</a>.&quot; Think of the DNS server as an internet address book. It quickly sends back the IP address.</li><li><strong>TCP/IP Handshake:</strong> Your computer uses the IP address to connect to the server through what’s called a “TCP” connection. This connection is made possible using “IP.” It’s like a virtual handshake, ensuring your computer and the server can talk.</li><li><strong>Firewall Check: </strong>If you have a firewall on your computer, it checks to make sure your request is allowed. The server you’re trying to reach might have a firewall too, and it also checks to allow the connection.</li><li><strong>Secure Connection (HTTPS):</strong> Your browser sends a request to the server using an encryption method like “SSL” or “TLS.” This encryption keeps the information you share between your computer and the server secure. It’s why you see the “s” in “https.”</li><li><strong>Load Balancer:</strong> Big companies like Google use multiple servers to handle lots of requests. They have a “load balancer” that directs requests to the right server. The load balancer is the traffic cop that ensures everything runs smoothly.</li><li><strong>Request and Response:</strong> Your browser’s request first goes to the load balancer, which forwards it to a specific server based on a specific algorithm. The server processes your request and sends a response back to the load balancer, which then passes it back to your browser.</li><li><strong>Webpage Components:</strong> The response typically includes HTML, CSS, and JavaScript files that create Google’s homepage. HTML tells your browser how to show the content, CSS styles it and JavaScript adds interactive features.</li><li><strong>Dynamic Content: </strong>If there’s dynamic content, like Google search results, the web server may ask the application server for data. The application server, in turn, could talk to a database server to get the needed data. This information is added to the response sent back to your browser.</li><li><strong>Rendering:</strong> Your browser takes all the components it receives and puts together the webpage you see on your screen. It’s like assembling a puzzle, and voilà, the page is ready for you.</li></ol><p>So, the next time you enter a web address, remember that all these steps happen in the blink of an eye to give you the website you want to visit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*_B4uIuSXqcLxyea4My5qxw.png" /></figure><p>Can you imagine all the steps happening before a webpage appears on your browser? The overview I just gave is just a quick summary of the process. Now, let’s take our time to explore each part in detail and see what goes on behind the scenes.</p><h3>DNS Request Simplified:</h3><p>Before your browser can even think about loading a website, it needs to know the web server’s address. Here’s how it figures it out:</p><ol><li><strong>Checking the Browser’s Memory:</strong> When you type a web address like “<a href="http://google.com/">google.com</a>,” your browser first looks in its memory to see if it remembers the address from before.</li><li><strong>Cached Copy:</strong> If your browser finds the address, it uses it, which is faster. This memory is called a DNS record.</li><li><strong>No Memory, No Problem: </strong>If your browser doesn’t remember or if the address has changed, it asks the DNS server for help.</li></ol><p>The Detailed DNS Lookup Process:</p><p>Here’s what happens when your browser asks for help from the DNS server:</p><ol><li><strong>Local DNS Resolver:</strong> Your browser talks to the local DNS resolver, usually provided by your internet service provider (ISP). It’s like asking a local guide for directions.</li><li><strong>Checking the Local Memory:</strong> The local DNS resolver also checks if it remembers the address. If it does, it tells your browser right away.</li><li><strong>Going Up the Chain: </strong>If the local DNS resolver doesn’t remember, it sends a request to the top-level directory, called the root nameserver. Think of it as asking for directions from the very top.</li><li><strong>Top-Level Directory:</strong> The root nameserver points to the top-level domain (TLD) nameserver, like “.com” or “.org.”</li><li><strong>TLD Directory:</strong> The TLD nameserver then guides your request to the authoritative nameserver for the specific domain.</li><li><strong>Authoritative Guide:</strong> The authoritative nameserver knows the address you need and provides it.</li><li><strong>Success!:</strong> The local DNS resolver now has the address and shares it with your browser.</li><li><strong>Browser’s Turn:</strong> Your browser finally knows where the website is and sends a request to the server at that address to get the webpage.</li></ol><p>In some cases, there can be extra steps if the DNS record isn’t found or if the website uses things like DNS load balancing or content delivery networks (CDN).</p><p>Once your browser knows the address, it keeps it for a while (the “TTL” or Time To Live) so that it can find the website faster the next time. The length of time it remembers is set by the website’s owner.</p><h3>TCP/IP Connection Simplified:</h3><p>TCP (Transmission Control Protocol) and IP (Internet Protocol) are like the internet’s handshake. They work together to connect your computer to a web server.</p><p>Here’s how it works:</p><ol><li><strong>Asking for a Connection:</strong> When you enter “<a href="http://google.com/">google.com</a>” in your browser, it uses TCP/IP to ask the server for a connection.</li><li><strong>Shake Hands:</strong> The server agrees to connect and sends a message back. This is like a digital handshake.</li><li><strong>Requesting the Webpage:</strong> Once the handshake is done, your browser asks for the webpage you want (like Google’s homepage). It uses TCP to make sure the request is sent and received correctly.</li><li><strong>Getting the Webpage:</strong> The server sends back the webpage’s code, using TCP again to make sure it arrives safely.</li><li><strong>Putting It All Together: </strong>Your browser takes the code and shows you the webpage on your screen. It uses TCP/IP to fetch any other stuff the webpage needs, like images.</li></ol><p>TCP/IP makes sure everything gets to your browser in the right order and without errors, so you see a complete and working webpage.</p><h3>Firewall Simplified :</h3><p>A firewall is like a digital security guard for your network. It watches the traffic coming in and going out and follows specific security rules to protect your network from things like hackers and harmful software.</p><p>When you type a web address like “<a href="http://google.com/">google.com</a>” in your browser, the request goes through the firewall on its way to the website’s server. The firewall checks the request to see if it’s okay based on its security rules.</p><p>There are two main types of rules the firewall uses:</p><ol><li><strong>Where is it from and where is it going?:</strong> The firewall checks if the request is coming from a safe place and going to the right place. For example, it might block requests from certain countries or only let in requests from certain known places.</li><li><strong>What type of request is it?:</strong> The firewall also checks what kind of traffic the request is. It might block certain types, like those used by bad software, or only allow known and safe types, like web browsing.</li></ol><p>If the request meets the firewall’s security rules, it’s allowed, and your browser can access the website. But if it doesn’t meet the rules, it’s blocked, and your browser can’t get to the site. Firewalls help keep your network safe from unwanted or harmful stuff.</p><h3>HTTPS/SSL :</h3><p>HTTPS (Hypertext Transfer Protocol Secure) is a secure version of the HTTP protocol used to transmit data on the internet. It is used to encrypt the data transmitted between your browser and Google’s server.</p><p>SSL (Secure Sockets Layer) and TLS (Transport Layer Security) are encryption protocols that are used to secure the data transmitted over HTTPS.</p><p>When your browser establishes a connection with Google’s server using HTTPS, your browser and Google’s server first agree on the version of SSL/TLS to use and then create a secure, encrypted channel for transmitting the data.</p><p>Let me use an analogy to explain what is going on here.</p><p>HTTPS is like a locked box that is used to send messages over the internet. When you want to send a message using HTTPS, you put the message in the locked box and send it to the person you want to receive the message. Only the person you are sending the message to has the key to unlock the box and read the message.</p><p>SSL/TLS are like special codes that are used to lock and unlock the box. When you want to send a message using HTTPS, you and the person you are sending the message to agree on the code to use to lock and unlock the box. This way, only you and the person you are sending the message to know the code and can read the message.</p><p>When you type “<a href="http://google.com/">google.com</a>” into your browser, the browser is like the person sending the message. The server that hosts <a href="http://google.com/">google.com</a> is like the person receiving the message. The browser sends a request for the webpage using HTTPS, which is like putting the request in the locked box and sending it to the server. The server then sends the webpage back to the browser using HTTPS, which is like putting the webpage in the locked box and sending it back to the browser.</p><h3>Load-Balancer :</h3><p>Think of a load balancer as a traffic cop for the internet. Its job is to make sure that when you visit a website, the work is shared evenly among all the servers, sort of like distributing the load.</p><p>Imagine a giant website like Google, with billions of visitors every day. To handle all this traffic, Google uses many servers. A load balancer helps make sure no one server gets too overloaded, and the website keeps running smoothly.</p><p>So, when you want to go to “<a href="http://google.com/">google.com</a>,” the load balancer takes your request and decides which server should handle it. This choice depends on a special rule called a load-balancing algorithm. This way, every server shares the work, and the website works well for everyone.</p><h3>Web Server :</h3><p>A web server is like the host at a restaurant. It’s in charge of taking your order (request for a web page) and making sure you get the right meal (web page) in return.</p><p>So, when you want to visit “<a href="http://google.com/">google.com</a>,” the server at Google gets the request from the load balancer. It then prepares the web page you asked for, including the HTML, CSS, and JavaScript that make it work.</p><p>Once it’s done, the web server sends this prepared web page back to the load balancer. The load balancer forwards it to your browser, and your browser uses all those ingredients (HTML, CSS, and JavaScript) to show you the web page you wanted.</p><h3>Application Server and Database :</h3><p>While the web server handles the basic web page, the application server deals with the dynamic stuff. For example, when you search on Google, the application server takes care of finding the right results for your query.</p><p>Here’s how it works:</p><ol><li><strong>Sending a Search:</strong> When you search on Google, your request goes to the load balancer, which forwards it to one of Google’s web servers. This web server then sends the request to the application server.</li><li><strong>Processing the Request: </strong>The application server takes your search query and figures out what results to show. If it’s a complex query, like searching for a product on an online store, it might need help from a database to find the right information.</li><li><strong>Database Help: </strong>For instance, if you’re looking for a specific product, the application server might ask the database for details about that product.</li><li><strong>Getting the Data: </strong>Once the application server has the data it needs, it sends it back to the web server. The web server then includes this data in the response it sends to your browser.</li><li><strong>Showing You the Results:</strong> Your browser uses this information to display the search results on your screen.</li></ol><p>So, while the web server handles the basics, the application server and the database, when needed, work together to give you dynamic content, like search results that change based on your query.</p><h3>Rendering the Page :</h3><p>When your browser gets the response from the web server, it’s like receiving a package with all the pieces of a puzzle. Inside are the HTML, CSS, and JavaScript files that make up the webpage.</p><p>Here’s what happens:</p><ul><li><strong>Arranging Content:</strong> Your browser places text and images where they belong on the page.</li><li><strong>Styling Everything: </strong>It ensures everything looks nice by following CSS styles.</li><li><strong>Making It Interactive:</strong> If there’s JavaScript, your browser runs it, enabling buttons and dynamic effects.</li></ul><p>Once your browser has done all this, you see the fully rendered webpage on your screen. Now you can click links, type in forms, and interact with the webpage as you please. It’s like putting together a puzzle, and the webpage becomes alive for you to use.</p><h3>Conclusion</h3><p>In the world of web browsing, a simple click of the “Enter” key initiates a fascinating journey through the digital realm. From DNS requests to the rendering of web pages, numerous components work together seamlessly. DNS servers find addresses, load balancers distribute work, firewalls secure the path, HTTPS/SSL encrypts data, web and application servers provide content, and your browser assembles the final page. This process makes the internet an accessible and dynamic resource for all.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ee2343d8c21" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL For Beginners]]></title>
            <link>https://medium.com/@johnnyJK/sql-for-beginners-3852b93d860e?source=rss-e496b7ee65a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/3852b93d860e</guid>
            <category><![CDATA[relational-databases]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[sql-for-beginners]]></category>
            <category><![CDATA[mysql-server]]></category>
            <dc:creator><![CDATA[John Kamau]]></dc:creator>
            <pubDate>Thu, 07 Sep 2023 10:22:26 GMT</pubDate>
            <atom:updated>2023-09-07T10:22:26.348Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fqKfJURUrSVYwInvunT9zw.jpeg" /></figure><h3>Introduction to SQL</h3><p>Structured Query Language (SQL) is a standardized programming language that is used to manage relational databases and perform various operations on the data in them. A relational database organizes data into rows and columns, which collectively form a table. Data is typically structured across multiple tables, which can be joined together via a primary key or a foreign key. These special keys demonstrate the different relationships that exist between tables.</p><p>SQL operates as a programming language by providing commands and a precise syntax to execute a variety of operations.</p><p>SQL commands can be categorized into various types, including:</p><ol><li>Data Definition Language (DDL) Commands: These commands are used for defining data tables. They create, alter, or remove database structures. They’re like the architects of the database.</li><li>Data Manipulation Language (DML) Commands: These commands deal with the data stored in the tables. They’re used to add, modify, or delete data. DML commands are like the workers who maintain the building.</li><li>Data Query Language (DQL) Commands: This consists mainly of the SELECT command, which is used to fetch specific data from the tables. It’s like asking for information from a database.</li><li>Data Control Language (DCL) Commands: These commands manage user access privileges. They grant or revoke permissions for data access. Think of them as security guards controlling who enters the building.</li><li>Transaction Control Language (TCL) Commands: These commands handle transactions. They manage changes in data states, such as committing or undoing changes. They’re like keeping track of changes made to the building.</li></ol><h3>Relational Database Management Systems</h3><p>While a relational database organizes data based off a relational data model, a relational database management system (RDBMS) is a more specific reference to the underlying database software that enables users to maintain it. These programs allow users to create, update, insert, or delete data in the system, and they provide: -Data structure, Multi-user access, Privilege control &amp; Network access.</p><p>Examples of popular RDBMS systems include MySQL, PostgreSQL, and IBM DB2. Additionally, a relational database system differs from a basic database management system (DBMS) in that it stores data in tables while a DBMS stores information as files.</p><h3>MySQL</h3><p>MySQL is an open-source Relational Database Management System (RDBMS) that enables users to store, manage, and retrieve structured data efficiently. It is widely used for various applications, from small-scale projects to large-scale websites and enterprise-level solutions.</p><p>RDBMS and MySQL are often thought to be the same because of MySQL’s popularity. A few big web applications like Facebook, Twitter, YouTube, Google, and Yahoo! all use MySQL for data storage purposes. Even though it was initially created for limited usage, it is now compatible with many important computing platforms like Linux, macOS, Microsoft Windows, and Ubuntu.</p><p>MySQL and SQL are distinct entities. MySQL is a popular brand of RDBMS software using a client-server model, written in C and C++. It utilizes the Structured Query Language (SQL) for communication between the client and server. Similarly, PostgreSQL and Microsoft SQL Server are other RDBMS brands that employ SQL as their primary language for database interaction, even though they’re implemented differently.</p><h3>Installing and Starting MySQL</h3><p>There are various ways to install MySQL on your operating system. Follow this link for guidance on <a href="https://dev.mysql.com/doc/mysql-getting-started/en/">installing and configuring MySQL server</a> on your local machine.</p><p>Once you are connected to the MySQL server, a welcome message is displayed and the mysql&gt; prompt appears, which looks like this:</p><pre>Welcome to the MySQL monitor.  Commands end with ; or \g.<br>Your MySQL connection id is 4<br>Server version: 5.7.32 MySQL Community Server (GPL)<br><br>Copyright (c) 2000, 2020, Oracle and/or its affiliates.<br><br>Oracle is a registered trademark of Oracle Corporation and/or its<br>affiliates. Other names may be trademarks of their respective<br>owners.<br><br>Type &#39;help;&#39; or &#39;\h&#39; for help. Type &#39;\c&#39; to clear the current input statement.<br><br>mysql&gt;</pre><p>To disconnect from the MySQL server, type QUIT or \q</p><pre>mysql&gt; QUIT</pre><blockquote>Note: In this article, we will use MySQL to facilitate the learning of SQL.</blockquote><h3>MySQL Data Types</h3><p>Here are some of the common MySQL data types :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*cJkujbnpwTNI6Z9e0CUsbQ.png" /></figure><h3>Basic SQL Queries</h3><p>SQL is designed for accessing, modifying, and extracting information from relational databases. As a programming language, SQL has commands and a syntax for issuing those commands. These commands, which adhere to SQL syntax, are referred to as SQL queries.</p><p>Showing existing databases. Use a SHOW DATABASES statement:</p><pre>mysql&gt; SHOW DATABASES;<br>+--------------------+<br>| Database           |<br>+--------------------+<br>| information_schema |<br>| mysql              |<br>| performance_schema |<br>| sys                |<br>+--------------------+<br>4 rows in set (0.00 sec)</pre><p>Creating a new database. Use a CREATE DATABASE statement:</p><pre>mysql&gt; CREATE DATABASE library;<br>Query OK, 1 row affected (0.02 sec)</pre><p>Check if the database has been created:</p><pre>mysql&gt; SHOW DATABASES;<br>+--------------------+<br>| Database           |<br>+--------------------+<br>| information_schema |<br>| library            |<br>| mysql              |<br>| performance_schema |<br>| sys                |<br>+--------------------+<br>5 rows in set (0.00 sec)</pre><p>Creating a table inside a database. First, pick the database in which you want to create the table with a USE statement:</p><pre>mysql&gt; USE library<br>Database changed</pre><p>The USE statement tells MySQL to use library as the default database for subsequent statements. Next, create a table with a CREATE TABLE statement:</p><pre>CREATE TABLE books<br>(<br>  id              INT unsigned NOT NULL AUTO_INCREMENT, # Unique ID for the record<br>  title           VARCHAR(100) NOT NULL,                # Name of the book<br>  author          VARCHAR(50) NOT NULL,                 # Author of the book<br>  genre           VARCHAR(30) NOT NULL,                 # Genre of the book<br>  publication     DATE NOT NULL,                        # Date of book publication<br>  PRIMARY KEY     (id)                                  # Make the id the primary key<br>);</pre><p>Data types that are used in each column are explained in <a href="https://dev.mysql.com/doc/refman/8.0/en/data-types.html">Data Types</a>. <a href="https://dev.mysql.com/doc/refman/8.0/en/primary-key-optimization.html">Primary Key Optimization</a> explains the concept of a primary key. What follows a # on each line is a comment, which is ignored by the MySQL client.</p><p>Check if the table has been created with a SHOW TABLES statement:</p><pre>mysql&gt; SHOW TABLES;<br>+-------------------+<br>| Tables_in_library |<br>+-------------------+<br>| books             |<br>+-------------------+<br>1 row in set (0.00 sec)</pre><p>DESCRIBE shows information on all columns of a table:</p><pre>mysql&gt; DESCRIBE books;<br>+-------------+--------------+------+-----+---------+----------------+<br>| Field       | Type         | Null | Key | Default | Extra          |<br>+-------------+--------------+------+-----+---------+----------------+<br>| id          | int unsigned | NO   | PRI | NULL    | auto_increment |<br>| title       | varchar(100) | NO   |     | NULL    |                |<br>| author      | varchar(50)  | NO   |     | NULL    |                |<br>| genre       | varchar(30)  | NO   |     | NULL    |                |<br>| publication | date         | NO   |     | NULL    |                |<br>+-------------+--------------+------+-----+---------+----------------+<br>5 rows in set (0.00 sec)</pre><p>Adding records into a table. Use an INSERT INTO…VALUES statement:</p><pre>INSERT INTO books (title, author, genre, publication) VALUES<br>  (&#39;To Kill a Mockingbird&#39;, &#39;Harper Lee&#39;, &#39;Fiction&#39;, &#39;1960-07-11&#39;),<br>  (&#39;1984&#39;, &#39;George Orwell&#39;, &#39;Science Fiction&#39;, &#39;1949-06-08&#39;),<br>  (&#39;Pride and Prejudice&#39;, &#39;Jane Austen&#39;, &#39;Classic&#39;, &#39;1813-01-28&#39;),<br>  (&#39;The Hobbit&#39;, &#39;J.R.R. Tolkien&#39;, &#39;Fantasy&#39;, &#39;1937-09-21&#39;);</pre><p>Retrieving records from a table. Use a SELECT statement, and “*” to match all columns:</p><pre>mysql&gt; SELECT * FROM books;<br>+----+-----------------------+----------------+-----------------+-------------+<br>| id | title                 | author         | genre           | publication |<br>+----+-----------------------+----------------+-----------------+-------------+<br>|  1 | To Kill a Mockingbird | Harper Lee     | Fiction         | 1960-07-11  |<br>|  2 | 1984                  | George Orwell  | Science Fiction | 1949-06-08  |<br>|  3 | Pride and Prejudice   | Jane Austen    | Classic         | 1813-01-28  |<br>|  4 | The Hobbit            | J.R.R. Tolkien | Fantasy         | 1937-09-21  |<br>+----+-----------------------+----------------+-----------------+-------------+<br>4 rows in set (0.00 sec)</pre><p>To select specific columns and rows by a certain condition using the WHERE clause:</p><pre>mysql&gt; SELECT title, author FROM books WHERE genre = &#39;Fantasy&#39;;<br>+------------+----------------+<br>| title      | author         |<br>+------------+----------------+<br>| The Hobbit | J.R.R. Tolkien |<br>+------------+----------------+<br>1 row in set (0.00 sec)</pre><p>Deleting a record from a table. Use a DELETE statement to delete a record from a table, specifying the criterion for deletion with the WHERE clause:</p><pre>mysql&gt; DELETE FROM books WHERE genre=&#39;Classic&#39;;<br>Query OK, 1 row affected (0.01 sec)<br><br>mysql&gt; SELECT * FROM books;<br>+----+-----------------------+----------------+-----------------+-------------+<br>| id | title                 | author         | genre           | publication |<br>+----+-----------------------+----------------+-----------------+-------------+<br>|  1 | To Kill a Mockingbird | Harper Lee     | Fiction         | 1960-07-11  |<br>|  2 | 1984                  | George Orwell  | Science Fiction | 1949-06-08  |<br>|  4 | The Hobbit            | J.R.R. Tolkien | Fantasy         | 1937-09-21  |<br>+----+-----------------------+----------------+-----------------+-------------+<br>3 rows in set (0.00 sec)</pre><p>Adding or deleting a column from a table. Use an ALTER TABLE…ADD statement to add a column. You can use, for example, an AFTER clause to specify the location of the new column:</p><pre>mysql&gt; ALTER TABLE books ADD publication_language VARCHAR(20) AFTER genre;<br>Query OK, 0 rows affected (0.08 sec)<br>Records: 0  Duplicates: 0  Warnings: 0</pre><p>In this example, we’re adding a new column named ‘publication_language’ to the ‘books’ table. Use DESCRIBE to check the result:</p><pre>mysql&gt; DESCRIBE books;<br>+----------------------+--------------+------+-----+---------+----------------+<br>| Field                | Type         | Null | Key | Default | Extra          |<br>+----------------------+--------------+------+-----+---------+----------------+<br>| id                   | int unsigned | NO   | PRI | NULL    | auto_increment |<br>| title                | varchar(100) | NO   |     | NULL    |                |<br>| author               | varchar(50)  | NO   |     | NULL    |                |<br>| genre                | varchar(30)  | NO   |     | NULL    |                |<br>| publication_language | varchar(20)  | YES  |     | NULL    |                |<br>| publication          | date         | NO   |     | NULL    |                |<br>+----------------------+--------------+------+-----+---------+----------------+<br>6 rows in set (0.00 sec)</pre><p>SHOW CREATE TABLE shows a CREATE TABLE statement, which provides even more details on the table:</p><p>COPY</p><pre>mysql&gt; SHOW CREATE TABLE books\G<br>*************************** 1. row ***************************<br>       Table: books<br>Create Table: CREATE TABLE `books` (<br>  `id` int unsigned NOT NULL AUTO_INCREMENT,<br>  `title` varchar(100) NOT NULL,<br>  `author` varchar(50) NOT NULL,<br>  `genre` varchar(30) NOT NULL,<br>  `publication_language` varchar(20) DEFAULT NULL,<br>  `publication` date NOT NULL,<br>  PRIMARY KEY (`id`)<br>) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci<br>1 row in set (0.00 sec)</pre><p>Use ALTER TABLE…DROP to delete a column:</p><pre>mysql&gt; ALTER TABLE books DROP COLUMN publication_language;<br>Query OK, 0 rows affected (0.10 sec)<br>Records: 0  Duplicates: 0  Warnings: 0<br><br>mysql&gt; DESCRIBE books;<br>+-------------+--------------+------+-----+---------+----------------+<br>| Field       | Type         | Null | Key | Default | Extra          |<br>+-------------+--------------+------+-----+---------+----------------+<br>| id          | int unsigned | NO   | PRI | NULL    | auto_increment |<br>| title       | varchar(100) | NO   |     | NULL    |                |<br>| author      | varchar(50)  | NO   |     | NULL    |                |<br>| genre       | varchar(30)  | NO   |     | NULL    |                |<br>| publication | date         | NO   |     | NULL    |                |<br>+-------------+--------------+------+-----+---------+----------------+<br>5 rows in set (0.01 sec)</pre><p>UPDATE…SET modifies existing data in a table:</p><pre>mysql&gt; UPDATE books SET genre = &#39;Dystopian Fiction&#39; WHERE title = &#39;1984&#39;;<br>Query OK, 1 row affected (0.01 sec)<br>Rows matched: 1  Changed: 1  Warnings: 0<br><br>mysql&gt; SELECT * FROM books;<br>+----+-----------------------+----------------+-------------------+-------------+<br>| id | title                 | author         | genre             | publication |<br>+----+-----------------------+----------------+-------------------+-------------+<br>|  1 | To Kill a Mockingbird | Harper Lee     | Fiction           | 1960-07-11  |<br>|  2 | 1984                  | George Orwell  | Dystopian Fiction | 1949-06-08  |<br>|  4 | The Hobbit            | J.R.R. Tolkien | Fantasy           | 1937-09-21  |<br>+----+-----------------------+----------------+-------------------+-------------+<br>3 rows in set (0.00 sec)</pre><p>These are a few fundamental SQL queries and commands that as a beginner you should become familiar with. In our next series, we’ll dive into more advanced SQL queries commonly employed in database management.</p><p>We will explore topics like subqueries, joins, stored procedures, and advanced data manipulation. These advanced queries will enable you to work with more complex data scenarios and become proficient in SQL.</p><h3>Conclusion</h3><p>In conclusion, SQL, with its fundamental queries and commands, serves as the cornerstone of database management for beginners. Understanding these basics provides a solid foundation for effectively interacting with and manipulating data.</p><p>As we journey into the world of more advanced SQL queries and techniques, we’ll unlock the true power of this language, enabling us to tackle complex data scenarios and harness the full potential of relational databases. Stay tuned for our upcoming series, where we explore the depths of SQL’s capabilities, opening doors to a world of data possibilities.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3852b93d860e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DATA STRUCTURES AND ALGORITHMS]]></title>
            <link>https://medium.com/@johnnyJK/data-structures-and-algorithms-907a63d691c1?source=rss-e496b7ee65a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/907a63d691c1</guid>
            <category><![CDATA[two-pointers]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[big-o-notation]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[data-structure-algorithm]]></category>
            <dc:creator><![CDATA[John Kamau]]></dc:creator>
            <pubDate>Wed, 06 Sep 2023 09:14:12 GMT</pubDate>
            <atom:updated>2023-09-06T09:14:12.625Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*Ce0Zq_Nxgn_IRU_3HiFSxg.jpeg" /></figure><h3><strong>Two Pointers Technique</strong></h3><p>The two-pointer technique is a fundamental algorithmic approach that plays a pivotal role in optimizing solutions to specific types of problems in computer science. This strategy involves the use of two pointers, often represented as indices or references, that traverse a data structure, such as an array, list, or string, simultaneously. By manipulating the positions of these two pointers , the technique aims to efficiently address a wide range of problems, making it a valuable tool in a programmer’s toolkit.</p><p>There are several ways to implement two-pointers. To start, let’s look at the following method:</p><blockquote><em>Start the pointers at the edges of the input. Move them towards each other until they meet.</em></blockquote><p>Converting this idea into instructions:</p><ol><li>Start one pointer at the first index 0 and the other pointer at the last index input.length - 1.</li><li>Use a while loop until the pointers are equal to each other.</li><li>At each iteration of the loop, move the pointers towards each other. This means either increment the pointer that started at the first index, decrement the pointer that started at the last index, or both. Deciding which pointers to move will depend on the problem we are trying to solve.</li></ol><p>Here’s some pseudocode illustrating the concept:</p><pre>function fn(arr):<br>    left = 0<br>    right = arr.length - 1<br><br>    while left &lt; right:<br>        Do some logic here depending on the problem<br>        Do some more logic here to decide on one of the following:<br>            1. left++<br>            2. right--<br>            3. Both left++ and right--</pre><p>The strength of this technique is that we will never have more than <em>O</em>(<em>n</em>) iterations for the while loop because the pointers start <em>n</em> away from each other and move at least one step closer in every iteration. Therefore, if we can keep the work inside each iteration at <em>O</em>(1), this technique will result in a linear runtime, which is usually the best possible runtime.</p><p>Let’s look at some of the use cases of this technique:</p><blockquote><strong>Example 1: Given a string </strong><strong>s, return </strong><strong>true if it is a palindrome, </strong><strong>false otherwise.</strong></blockquote><blockquote><strong>A string is a palindrome if it reads the same forward as backward. That means, after reversing it, it is still the same string. For example: “abcdcba”, or “racecar”.</strong></blockquote><p><strong>Method 1: </strong>Naïve Approach</p><p>The most straightforward way to check if a string is a palindrome is to reverse it and compare it to the original string. If they match, we have a palindrome. If not, the string is not a palindrome.</p><p>Pseudocode:</p><pre>function isPalindrome(s):<br>    reversedS = reverse(s)<br>    if s == reversedS:<br>        return true<br>    else:<br>        return false</pre><p>Explanation:</p><ol><li>We start by reversing the input string s using a function reverse(s).</li><li>Then, we compare the original string s with the reversed string reversedS.</li><li>If they are identical, we return true, indicating that s is a palindrome. Otherwise, we return false.</li></ol><p><strong>JavaScript Code:</strong></p><pre>function isPalindrome(s) {<br>    // convert to lowercase<br>    s = s.toLowerCase();<br><br>    // Reverse the input string<br>    const reversedS = s.split(&#39;&#39;).reverse().join(&#39;&#39;);<br>    <br>    // Compare the original string with the reversed string<br>    return s === reversedS;<br>}<br><br>// Test cases<br>const string1 = &quot;racecar&quot;;<br>const string2 = &quot;Radar&quot;;<br><br>console.log(isPalindrome(string1)); // Output: true<br>console.log(isPalindrome(string2)); // Output: true</pre><p>Complexity Analysis:</p><ul><li>Time Complexity: Reversing a string takes O(n) time, where n is the length of the string. The comparison also takes O(n) time. Therefore, the overall time complexity is O(n).</li><li>Space Complexity: We need additional space to store the reversed string, which takes O(n) space. So, the space complexity is O(n).</li></ul><p>The naïve approach provides a simple and intuitive way to check if a string is a palindrome. However, it has room for optimization, as we are using extra space and performing unnecessary comparisons</p><p><strong>Method 2:</strong> Two Pointers Technique</p><p>The two-pointer technique is a clever strategy that leverages the fact that for a palindrome string, the first character is the same as the last character, the second character is the same as the second last character, and so on. By using two pointers, one starting from the beginning of the string and the other from the end, we can efficiently check if all corresponding characters are equal. If we find a mismatch at any point, we can immediately conclude that the string is not a palindrome.</p><p><strong>JavaScript Code:</strong></p><pre>function isPalindrome(s) {<br>    let left = 0;             // Pointer starting from the beginning<br>    let right = s.length - 1; // Pointer starting from the end<br>    <br>    while (left &lt; right) {<br>        // Compare the characters at the left and right pointers, ignoring case<br>        if (s[left].toLowerCase() !== s[right].toLowerCase()) {<br>            return false; // Mismatch found, not a palindrome<br>        }<br>        <br>        // Move the pointers towards each other<br>        left++;<br>        right--;<br>    }<br>    <br>    return true; // No mismatch found, it&#39;s a palindrome<br>}<br><br>// Test cases<br>const string1 = &quot;racecar&quot;;<br>const string2 = &quot;Radar&quot;;<br><br>console.log(isPalindrome(string1)); // Output: true<br>console.log(isPalindrome(string2)); // Output: true</pre><p>Notice that if the input was an array of characters instead of a string, the algorithm wouldn’t change. The two-pointers technique works as long as the index variables are moving along some abstract iterable.</p><p>This algorithm is very efficient as not only does it run in <strong><em>O</em>(<em>n</em>)</strong>, but it also uses only <strong><em>O</em>(1) </strong>space. No matter how big the input is, we always only use two integer variables. The time complexity is <em>O</em>(<em>n</em>) because the while loop iterations cost <em>O</em>(1) each, and there can never be more than <em>O</em>(<em>n</em>) iterations of the while loop — the pointers start at a distance of <em>n</em> from each other and move closer by one step each iteration.</p><blockquote><strong>Example 2: Given a sorted array of unique integers and a target integer, return </strong><strong>true if there exists a pair of numbers that sum to target, </strong><strong>false otherwise. This problem is similar to </strong><a href="https://leetcode.com/problems/two-sum/"><strong>Two Sum</strong></a><strong>. (In Two Sum, the input is not sorted).</strong></blockquote><blockquote><strong>For example, given </strong><strong>nums = [1, 2, 4, 6, 8, 9, 14, 15] and </strong><strong>target = 13, return true because </strong><strong>4 + 9 = 13.</strong></blockquote><p><strong>Method 1: </strong>Brute Force<strong> </strong>Approach</p><p>The brute force approach involves checking all possible pairs of numbers in the sorted array to see if any of them add up to the target integer. Although this method is not the most efficient, it can serve as a baseline for understanding the problem.</p><p>Pseudocode:</p><pre>function hasPairWithSum(nums, target):<br>    n = length of nums<br>    for i from 0 to n-2:<br>        for j from i+1 to n-1:<br>            if nums[i] + nums[j] == target:<br>                return true<br>    return false</pre><p>Explanation:</p><ol><li>We initialize a variable n to store the length of the input array nums.</li><li>We use two nested loops to iterate through all possible pairs of numbers in the array, represented by indices i and j.</li><li>For each pair, we check if the sum of nums[i] and nums[j] equals the target integer.</li><li>If a pair is found that satisfies the condition, we return true, indicating that there exists a pair with the desired sum.</li><li>If no such pair is found after checking all possible pairs, we return false.</li></ol><p><strong>JavaScript code:</strong></p><pre>function hasPairWithSum(nums, target) {<br>    const n = nums.length;<br><br>    for (let i = 0; i &lt; n - 1; i++) {<br>        for (let j = i + 1; j &lt; n; j++) {<br>            if (nums[i] + nums[j] === target) {<br>                return true;<br>            }<br>        }<br>    }<br><br>    return false;<br>}<br><br>// Example usage:<br>const nums = [1, 2, 4, 6, 8, 9, 14, 15];<br>const target = 13;<br>const result = hasPairWithSum(nums, target);<br>console.log(result); // Output: true (4 + 9 = 13)</pre><p>Complexity Analysis:</p><ul><li>Time Complexity: The brute force approach checks all possible pairs of numbers, resulting in a time complexity of O(n²), where n is the number of elements in the array.</li><li>Space Complexity: The algorithm uses a constant amount of additional space, so the space complexity is O(1).</li></ul><p>While this approach works, it may not be efficient for large input arrays due to its quadratic time complexity.</p><p><strong>Method 2:</strong> Two Pointers Technique</p><p>Let’s use the example input. With two pointers, we start by looking at the first and last number. Their sum is 1 + 15 = 16. Because 16 &gt; target, we need to make our current sum smaller. Therefore, we should move the right pointer. Now, we have 1 + 14 = 15. Again, move the right pointer because the sum is too large. Now, 1 + 9 = 10. Since the sum is too small, we need to make it bigger, which can be done by moving the left pointer. 2 + 9 = 11 &lt; target, so move it again. Finally, 4 + 9 = 13 = target.</p><p>The reason this algorithm works: because the numbers are sorted, moving the left pointer permanently increases the value the left pointer points to (nums[left] = x). Similarly, moving the right pointer permanently decreases the value the right pointer points to (nums[right] = y). If we have x + y &gt; target, then we can never have a solution with y because x can only increase. So if a solution exists, we can only find it by decreasing y. The same logic can be applied to x if x + y &lt; target.</p><p><strong>JavaScript Code:</strong></p><pre>function hasPairWithSum(nums, target) {<br>    let left = 0;             // Pointer starting from the beginning<br>    let right = nums.length - 1; // Pointer starting from the end<br>    <br>    while (left &lt; right) {<br>        const sum = nums[left] + nums[right];<br>        <br>        if (sum === target) {<br>            return true; // Pair found, return true<br>        } else if (sum &lt; target) {<br>            left++; // Move the left pointer to increase the sum<br>        } else {<br>            right--; // Move the right pointer to decrease the sum<br>        }<br>    }<br>    <br>    return false; // No pair found, return false<br>}<br><br>const nums = [1, 2, 4, 6, 8, 9, 14, 15];<br>const target = 13;<br><br>const result = hasPairWithSum(nums, target);<br>console.log(result); // Output: true (4 + 9 = 13)</pre><p>This algorithm uses <em>O</em>(1) space and has a time complexity of <em>O</em>(<em>n</em>).</p><h3>Another Two Pointer Technique approach</h3><p>This method where we start the pointers at the first and last indices and move them towards each other is only one way to implement two pointers. Algorithms are beautiful because of how abstract they are — “two pointers” is just an idea, and it can be implemented in many ways. Let’s look at another method.</p><p>The following method is applicable when the problem has two iterables in the input, for example, two arrays.</p><blockquote><strong>Example 3: Given two sorted integer arrays </strong><strong>arr1 and </strong><strong>arr2, return a new array that combines both of them and is also sorted.</strong></blockquote><p>The trivial approach would be to first combine both input arrays and then perform a sort. If we have n = arr1.length + arr2.length, then this gives a time complexity of O(<em>n</em>⋅log<em>n</em>) (the cost of sorting). This would be a good approach if the input arrays were not sorted, but because they are sorted, we can take advantage of the two-pointers technique to improve to <em>O</em>(<em>n</em>).</p><p><strong>Solution:</strong> Two-pointers technique</p><p>We can build the answer array ans one element at a time. Start two pointers at the first index of each array, and compare their elements. At each iteration, we have 2 values. Whichever value is lower needs to come first in the answer, so add it to the answer and move the respective pointer.</p><p><strong>Javascript Code:</strong></p><pre>var combine = function(arr1, arr2) {<br>    // Initialize an empty array to store the merged result<br>    let ans = [];<br>    // Initialize two pointers for arr1 and arr2<br>    let i = 0, j = 0;<br>    <br>    // Loop until we reach the end of either arr1 or arr2<br>    while (i &lt; arr1.length &amp;&amp; j &lt; arr2.length) {<br>        // Compare the current elements at arr1[i] and arr2[j]<br>        if (arr1[i] &lt; arr2[j]) {<br>            // If arr1[i] is smaller, push it to the result and move the arr1 pointer<br>            ans.push(arr1[i]);<br>            i++;<br>        } else {<br>            // If arr2[j] is smaller or equal, push it to the result and move the arr2 pointer<br>            ans.push(arr2[j]);<br>            j++;<br>        }<br>    }<br>    <br>    // If there are remaining elements in arr1, append them to the result<br>    while (i &lt; arr1.length) {<br>        ans.push(arr1[i]);<br>        i++;<br>    }<br>    <br>    // If there are remaining elements in arr2, append them to the result<br>    while (j &lt; arr2.length) {<br>        ans.push(arr2[j]);<br>        j++;<br>    }<br>    <br>    // Return the merged and sorted array<br>    return ans;<br>}</pre><p>Like in the previous two examples, this algorithm has a time complexity of <em>O</em>(<em>n</em>) and uses <em>O</em>(1) space (if we don’t count the output as extra space, which we usually don’t).</p><p><strong>Concluding Remarks:</strong></p><p>It’s crucial to recognize that the techniques discussed here serve as valuable guidelines rather than rigid rules. The specific problem you encounter may require a tailored approach. For instance, in the first method, we initiated the pointers at the first and last index, but some situations might demand a different starting point for the pointers. Similarly, the second method involves moving two pointers forward along separate inputs, but there are scenarios where you may deal with a single input, yet still start both pointers at the first index and advance them in tandem.</p><p>The term “two pointers” essentially refers to the utilization of two integer variables for traversing through iterable structures. While the strategies covered in this article are prevalent and effective, it’s essential to remain open to alternative problem-solving approaches. Some problems even necessitate the application of “three pointers” or similar variations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=907a63d691c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Object Oriented Programming in Python]]></title>
            <link>https://medium.com/@johnnyJK/object-oriented-programming-in-python-761ad14b114e?source=rss-e496b7ee65a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/761ad14b114e</guid>
            <category><![CDATA[object-oriented-program]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[oop-python]]></category>
            <category><![CDATA[oop-concepts]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[John Kamau]]></dc:creator>
            <pubDate>Mon, 04 Sep 2023 17:14:24 GMT</pubDate>
            <atom:updated>2023-09-04T17:14:24.930Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3G1Ex7zSCyYJN1a8RA1qcw.png" /></figure><p>Object-Oriented Programming (OOP) is a programming paradigm that organizes code into objects, which are instances of classes. These objects encapsulate data and behavior, allowing developers to model real-world entities and interactions effectively. OOP in Python revolves around four main principles: encapsulation, inheritance, polymorphism, and abstraction.</p><p>Overall, OOP in Python enables developers to create modular, organized, and scalable code. It promotes the design of complex systems using smaller, reusable, and understandable building blocks.</p><h3>Classes and Objects</h3><p>Python is a powerful object-oriented programming language that allows you to create classes to define and manage objects. In Python, built-in classes represent the most commonly used data types, like strings, lists, and dictionaries.</p><p>A class in Python serves as a blueprint or template for creating objects. It consists of instance variables, which are like attributes, and related methods that define the behavior of the objects.</p><p>On the other hand, an object is a specific instance of a class, possessing a unique set of properties defined by the class. The great thing is that you can create multiple objects based on the same class, each with its own distinct characteristics.</p><p>Now, let’s illustrate the concept of a class by defining one for an “Electronic Shop” software application. This class, called “Electronic,” will be used to create electronic items that the shop sells.</p><pre>class Electronic:<br>    def __init__(self, name, brand, price, quantity):<br>        self.name = name<br>        self.brand = brand<br>        self.price = price<br>        self.quantity = quantity</pre><p>The __init__ special method, also known as a Constructor, is used to initialize the Book class with attributes such as name, brand, price and quantity.</p><p>In Python, built-in classes are named in lowercase, but user-defined classes are named in Camel or Snake case, with the first letter capitalized.</p><p>This class can be instantiated to any number of objects. Three Electronics are instantiated in the following example code:</p><pre>electronic1 = Electronic(&quot;Laptop&quot;, &quot;Dell&quot;, 1200, 5)<br>electronic2 = Electronic(&quot;Smartphone&quot;, &quot;Samsung&quot;, 800, 10)<br>electronic3 = Electronic(&quot;Headphones&quot;, &quot;Sony&quot;, 150, 20)<br><br>print(electronic1)<br>print(electronic2)<br>print(electronic3)</pre><p>Output:</p><pre>&lt;__main__.Electronic object at 0x7fe16f95ae50&gt;<br>&lt;__main__.Electronic object at 0x7fe16f95b510&gt;<br>&lt;__main__.Electronic object at 0x7fe16f95b550&gt;</pre><p>In Python, when objects are printed, the default output shows the class and memory location, lacking specific details like the name or brand. To address this, we can use a special method named __repr__.</p><p>Special methods in Python are functions denoted by names starting and ending with double underscores ( __ ). They are automatically invoked under specific conditions, enabling us to customize object behavior.</p><p>By implementing the __repr__ method within a class, we can control how the object is represented as a string when it is printed or when the repr() function is called. This empowers us to display particular information about the object&#39;s attributes and qualities in a more meaningful manner.</p><pre>class Electronic:<br>    def __init__(self, name, brand, price, quantity):<br>        self.name = name<br>        self.brand = brand<br>        self.price = price<br>        self.quantity = quantity<br><br>    def __repr__(self):<br>        return f&quot;Electronic(name=&#39;{self.name}&#39;, brand=&#39;{self.brand}&#39;, price={self.price}, quantity={self.quantity})&quot;<br><br># Instantiate an example of Electronic<br>electronic1 = Electronic(&quot;Laptop&quot;, &quot;Dell&quot;, 1200, 5)<br><br># Print the object, now using the __repr__ method<br>print(electronic1)</pre><p>Output:</p><pre>Electronic(name=&#39;Laptop&#39;, brand=&#39;Dell&#39;, price=1200, quantity=5)</pre><h3>OOP Principles:</h3><p>There are four Object-Oriented Programming core principles:-</p><ul><li>Encapsulation</li><li>Inheritance</li><li>Polymorphism</li><li>Abstraction</li></ul><h3>Data Encapsulation</h3><p>Encapsulation is a concept in programming that protects certain properties of an object, ensuring that they can only be accessed and modified through designated class/object methods.</p><p>Private attributes are properties that are not directly accessible from outside the class, and they are hidden from external manipulation. To achieve this, we declare private attributes by adding two underscores before their names.</p><p>In our Electronic class, we will employ encapsulation by introducing a private attribute named __discount</p><pre>class Electronic:<br>    def __init__(self, name, brand, price, quantity):<br>        self.name = name<br>        self.brand = brand<br>        self.price = price<br>        self.quantity = quantity<br>        self.__discount = 0.10<br><br>    def __repr__(self):<br>        return f&quot;Electronic(name=&#39;{self.name}&#39;, brand=&#39;{self.brand}&#39;, price={self.price}, quantity={self.quantity})&quot;<br><br># Instantiate an example of Electronic<br>electronic1 = Electronic(&quot;Laptop&quot;, &quot;Dell&quot;, 1200, 5)<br><br>print(electronic1.name)<br>print(electronic1.brand)<br>print(electronic1.price)<br>print(electronic1.quantity)<br>print(electronic1.__discount)</pre><p>Output:</p><pre>Laptop<br>Dell<br>1200<br>5<br>Traceback (most recent call last):<br>  File &quot;/home/john/Documents/test/test.py&quot;, line 20, in &lt;module&gt;<br>    print(electronic1.__discount)<br>          ^^^^^^^^^^^^^^^^^^^^^^<br>AttributeError: &#39;Electronic&#39; object has no attribute &#39;__discount&#39;</pre><p>You can see that all the attributes are printed except the private attribute __discount. We use getter and setter methods to access private attributes.</p><p>Let’s make the price property, private, and use a setter method to assign the discount attribute and a getter function to get the price attribute.</p><pre>class Electronic:<br>    def __init__(self, name, brand, price, quantity):<br>        self.name = name<br>        self.brand = brand<br>        self.__price = price<br>        self.quantity = quantity<br>        self.__discount = None<br><br>    def set_discount(self, discount):<br>        self.__discount = discount<br><br>    def get_price(self):<br>        if self.__discount:<br>            return self.__price * (1-self.__discount)<br>        return self.__price<br><br>    def __repr__(self):<br>        return f&quot;Electronic(name=&#39;{self.name}&#39;, brand=&#39;{self.brand}&#39;, price={self.get_price()}, quantity={self.quantity})&quot;</pre><p>Now let’s create two objects, one for the purchase of a single electronic and another for the purchase of an electronic in bulk quantity. While purchasing electronics in bulk quantity, we want to give a discount of 20%, so we’ll use the set_discount() method to set the discount to 20% in that case.</p><pre># Instantiate an examples of Electronics<br>one_laptop = Electronic(&quot;Laptop&quot;, &quot;Dell&quot;, 1200, 1)<br><br>multi_laptops = Electronic(&quot;Laptop&quot;, &quot;Acer&quot;, 1500, 10)<br>multi_laptops.set_discount(0.20)<br><br>print(one_laptop.get_price())<br>print(multi_laptops.get_price())<br>print(one_laptop)<br>print(multi_laptops)</pre><p>Output:</p><pre>1200<br>1200.0<br>Electronic(name=&#39;Laptop&#39;, brand=&#39;Dell&#39;, price=1200, quantity=1)<br>Electronic(name=&#39;Laptop&#39;, brand=&#39;Acer&#39;, price=1200.0, quantity=10)</pre><h3>Inheritance</h3><p>In object-oriented programming, inheritance is considered one of the most crucial features. It allows a class to acquire methods and attributes from another class, facilitating code reuse and promoting a hierarchical structure.</p><p>In the context of our Electronic shop software, we will introduce two new classes: Laptop and Phone. These classes represent different types of electronics, but they may share common attributes such as name and brand, as well as common methods like get_price() and set_discount(). Repeating the same code for each new class is inefficient and redundant in terms of time, effort, and memory utilization.</p><p>By utilizing inheritance, we can create a parent class that holds the common attributes and methods, and then have the Laptop and Phone classes inherit from this parent class. This way, we can avoid duplicating code and efficiently manage the shared functionality across various book types. The child classes will automatically gain access to the properties and behavior of the parent class, promoting code organization and reducing maintenance overhead.</p><pre>class Electronic:<br>    def __init__(self, name, brand, price, quantity):<br>        self.name = name<br>        self.brand = brand<br>        self.__price = price<br>        self.quantity = quantity<br>        self.__discount = None<br><br>    def set_discount(self, discount):<br>        self.__discount = discount<br><br>    def get_price(self):<br>        if self.__discount:<br>            return self.__price * (1-self.__discount)<br>        return self.__price<br><br>    def __repr__(self):<br>        return f&quot;Electronic, name:&#39;{self.name}&#39;, brand:&#39;{self.brand}&#39;, price:{self.get_price()}, quantity:{self.quantity}&quot;<br><br>class Laptop(Electronic):<br>    def __init__(self, name, brand, price, quantity, processor):<br>        super().__init__(name, brand, price, quantity)<br>        self.processor = processor<br><br>class Phone(Electronic):<br>    def __init__(self, name, brand, price, quantity, display_size):<br>        super().__init__(name, brand, price, quantity)<br>        self.display_size = display_size</pre><p>By using the super() function in the subclass constructors, we correctly call the parent class&#39;s __init__ method, allowing us to initialize the common attributes defined in the Electronic class.</p><pre>laptop1 = Laptop(&#39;XPS 15&#39;, &#39;Dell&#39;, 1800, 25, &#39;Intel Core i7&#39;)<br>laptop1.set_discount(0.15)<br><br>phone1 = Phone(&#39;Galaxy S20&#39;, &#39;Samsung&#39;, 800, 215, &#39;6.2 inches&#39;)<br>phone1.set_discount(0.22)<br><br>print(laptop1)<br>print(phone1)</pre><p>Output:</p><pre>Electronic, name:&#39;XPS 15&#39;, brand:&#39;Dell&#39;, price:1530.0, quantity:25<br>Electronic, name:&#39;Galaxy S20&#39;, brand:&#39;Samsung&#39;, price:624.0, quantity:215</pre><p>There are four common types of inheritance. In single inheritance, a class inherits from just one parent class, allowing it to access the parent’s properties and behavior. Multilevel inheritance involves classes forming a chain where each class derives from its immediate parent, passing down attributes and methods. Hierarchical inheritance features multiple classes inheriting from a single parent class, each adding its own attributes. In multiple inheritance, a class can inherit from multiple parent classes, gaining combined attributes and methods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UjGeQtKO36k25HGpOv9wgA.jpeg" /></figure><h3>Polymorphism</h3><p>Polymorphism is a concept rooted in the Greek language, signifying ‘something that takes on multiple forms.’</p><p>In programming, polymorphism pertains to the capability of a subclass to alter an existing method inherited from its superclass to suit its specific requirements. In essence, a subclass can either utilize a method from its superclass as it is or adjust it according to its needs. This flexibility allows for dynamic and versatile behavior in different instances of related classes, enhancing code reusability and adaptability.</p><pre>class Electronic:<br>    def __init__(self, name, brand, price, quantity):<br>        self.name = name<br>        self.brand = brand<br>        self.__price = price<br>        self.quantity = quantity<br>        self.__discount = None<br><br>    def set_discount(self, discount):<br>        self.__discount = discount<br><br>    def get_price(self):<br>        if self.__discount:<br>            return self.__price * (1-self.__discount)<br>        return self.__price<br><br>    def __repr__(self):<br>        return f&quot;Electronic, name:&#39;{self.name}&#39;, brand:&#39;{self.brand}&#39;, price:{self.get_price()}, quantity:{self.quantity}&quot;<br><br>class Laptop(Electronic):<br>    def __init__(self, name, brand, price, quantity, processor):<br>        super().__init__(name, brand, price, quantity)<br>        self.processor = processor<br><br>class Phone(Electronic):<br>    def __init__(self, name, brand, price, quantity, display_size):<br>        super().__init__(name, brand, price, quantity)<br>        self.display_size = display_size<br><br>    def __repr__(self):<br>        return f&quot;Phone, name:&#39;{self.name}&#39;, brand:&#39;{self.brand}&#39;, price:{self.get_price()}, display_size:{self.display_size}&quot;</pre><p>The superclass, “Electronic,” possesses a distinct method called __repr__. This method can be used by the &quot;Laptop&quot; subclass, effectively causing it to execute whenever an object is printed.</p><p>Contrastingly, the “Phone” subclass is equipped with its individual __repr__ special function, as seen in the provided example code. The &quot;Phone&quot; subclass leverages polymorphism to invoke its unique method, effectively overriding the corresponding method inherited from its superclass.</p><pre># Instantiate a Phone object<br>phone1 = Phone(&quot;Smartphone&quot;, &quot;Samsung&quot;, 1000, 2, 6.2)<br><br># Instantiate a Laptop object<br>laptop1 = Laptop(&quot;Notebook&quot;, &quot;HP&quot;, 800, 3, &quot;Intel i5&quot;)<br><br># Print the objects, invoking their respective __repr__ methods<br>print(phone1)<br>print(laptop1)</pre><p>Output:</p><pre>Phone, name:&#39;Smartphone&#39;, brand:&#39;Samsung&#39;, price:1000.0, display_size:6.2<br>Electronic, name:&#39;Notebook&#39;, brand:&#39;HP&#39;, price:800.0, quantity:3</pre><h3>Abstraction</h3><p>Abstraction in object-oriented programming simplifies things by focusing on the main aspects of classes or objects, hiding the nitty-gritty details. It makes using objects easier without needing to know all the complicated inner workings.</p><p>In Python, direct abstraction isn’t provided, but using magic methods enables abstraction. When an abstract method is defined in a superclass, subclasses inheriting from it must implement their versions of the method. Although a subclass won’t directly use the superclass’s abstract method, this abstraction enforces a consistent structure across all subclasses, contributing to better code organization and maintenance.</p><p>In our parent class <em>Electronic</em>, we have defined the __repr__ method. Let&#39;s make that method abstract, forcing every subclass to compulsorily have its own __repr__ method.</p><pre>from abc import ABC, abstractmethod<br><br><br>class Electronic(ABC):<br>    def __init__(self, name, brand, price, quantity):<br>        self.name = name<br>        self.brand = brand<br>        self.__price = price<br>        self.quantity = quantity<br>        self.__discount = None<br><br>    def set_discount(self, discount):<br>        self.__discount = discount<br><br>    def get_price(self):<br>        if self.__discount:<br>            return self.__price * (1-self.__discount)<br>        return self.__price<br><br>    @abstractmethod<br>    def __repr__(self):<br>        return f&quot;Electronic, name:&#39;{self.name}&#39;, brand:&#39;{self.brand}&#39;, price:{self.get_price()}, quantity:{self.quantity}&quot;<br><br>class Laptop(Electronic):<br>    def __init__(self, name, brand, price, quantity, processor):<br>        super().__init__(name, brand, price, quantity)<br>        self.processor = processor<br><br>class Phone(Electronic):<br>    def __init__(self, name, brand, price, quantity, display_size):<br>        super().__init__(name, brand, price, quantity)<br>        self.display_size = display_size<br><br>    def __repr__(self):<br>        return f&quot;Phone, name:&#39;{self.name}&#39;, brand:&#39;{self.brand}&#39;, price:{self.get_price()}, display_size:{self.display_size}&quot;<br><br># Instantiate a Laptop object<br>laptop1 = Laptop(&quot;Notebook&quot;, &quot;HP&quot;, 800, 3, &quot;Intel i5&quot;)<br><br># Instantiate a Phone object<br>phone1 = Phone(&quot;Smartphone&quot;, &quot;Samsung&quot;, 1000, 2, 6.2)<br><br># Print the objects<br>print(phone1)<br><br>print(laptop1)</pre><p>In the above code, we have inherited the <em>ABC</em> module to create the <em>Electronic Abstract</em> class. We’ve made the __repr__ method an abstract method by adding the @abstractmethod decorator.</p><p>In the Laptop class, we’ve intentionally missed the implementation of the __repr__ method to see what will happen.</p><p>Output:</p><pre>Traceback (most recent call last):<br>  File &quot;/home/john/Documents/test/test.py&quot;, line 41, in &lt;module&gt;<br>    laptop1 = Laptop(&quot;Notebook&quot;, &quot;HP&quot;, 800, 3, &quot;Intel i5&quot;)<br>              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^<br>TypeError: Can&#39;t instantiate abstract class Laptop with abstract method __repr__</pre><p>We get a TypeError saying we cannot instantiate an object of the Laptop class. Let’s add the implementation of the __repr__ method and see what happens now.</p><pre>class Laptop(Electronic):<br>    def __init__(self, name, brand, price, quantity, processor):<br>        super().__init__(name, brand, price, quantity)<br>        self.processor = processor<br><br>    def __repr__(self):<br>        return f&quot;Laptop, name:&#39;{self.name}&#39;, brand:&#39;{self.brand}&#39;, price:{self.get_price()}, processor:{self.processor}&quot;</pre><p>Output:</p><pre>Phone, name:&#39;Smartphone&#39;, brand:&#39;Samsung&#39;, price:1000.0, display_size:6.2<br>Laptop, name:&#39;Notebook&#39;, brand:&#39;HP&#39;, price:800.0, processor:Intel i5</pre><p>By creating an abstract base class Electronic and then extending it with concrete subclasses like Laptop and Phone, we&#39;ve showcased how abstraction allows us to define a common structure while enabling customization and specialization in the subclasses.</p><h3>Method Overloading</h3><p>Method overloading, a prevalent concept in object-oriented programming languages, involves employing multiple methods with the same name but differing numbers of arguments within a single class. This enables more flexibility in designing classes that can perform similar actions with distinct parameter combinations.</p><p>In Python, unlike some other languages, method overloading based on different argument counts is not directly supported. However, you can achieve similar functionality using default arguments or variable-length argument lists. Here are both approaches:</p><ol><li><strong>Using Default Arguments:</strong></li></ol><pre>class MathOperations:<br>    def add(self, a=0, b=0, c=0):<br>        return a + b + c<br><br># Create an instance<br>math_obj = MathOperations()<br><br># Call the method with different argument counts<br>print(math_obj.add())         # Output: 0<br>print(math_obj.add(1))        # Output: 1<br>print(math_obj.add(1, 2))     # Output: 3<br>print(math_obj.add(1, 2, 3))  # Output: 6</pre><p>2. <strong>Using Variable-Length Argument Lists (args):</strong></p><pre>class MathOperations:<br>    def add(self, *args):<br>        total = sum(args)<br>        return total<br><br># Create an instance<br>math_obj = MathOperations()<br><br># Call the method with different argument counts<br>print(math_obj.add())         # Output: 0<br>print(math_obj.add(1))        # Output: 1<br>print(math_obj.add(1, 2))     # Output: 3<br>print(math_obj.add(1, 2, 3))  # Output: 6</pre><p>While Python doesn’t have traditional method overloading like some languages, using default arguments or variable-length argument lists allows you to achieve similar results, adapting a method to handle different argument scenarios.</p><h3>Method Overriding</h3><p>When a method with identical name and arguments exists in both a derived (child) class and its base (parent) class, the method in the derived class is said to “override” the method from the base class.</p><p>Upon calling the overridden method, the implementation from the derived class takes precedence and is executed. Consequently, the method from the base class remains concealed or hidden from view during the call.</p><pre>class Shape:<br>    def area(self):<br>        return 0<br><br>class Circle(Shape):<br>    def __init__(self, radius):<br>        self.radius = radius<br><br>    def area(self):<br>        return 3.14 * self.radius * self.radius<br><br>class Square(Shape):<br>    def __init__(self, side):<br>        self.side = side<br><br>    def area(self):<br>        return self.side * self.side<br><br># Instantiate objects<br>circle = Circle(5)<br>square = Square(4)<br><br># Call the overridden methods<br>print(&quot;Area of Circle:&quot;, circle.area())  # Output: Area of Circle: 78.5<br>print(&quot;Area of Square:&quot;, square.area())  # Output: Area of Square: 16<br><br># Call the base class method<br>shape = Shape()<br>print(&quot;Area of Shape:&quot;, shape.area())  # Output: Area of Shape: 0</pre><p>In this example, the Shape class defines a method area(). Both the Circle and Square subclasses override this method with their own implementations. When calling the area() method on instances of Circle and Square, the overridden methods in the subclasses are invoked, showing how method overriding works.</p><h3>Conclusion</h3><p>In summary, this exploration of Python’s object-oriented programming concepts highlights the essence of OOP’s modularity and reusability. Encapsulation, inheritance, and polymorphism showcase its power, while abstraction simplifies complexity. Method overloading and overriding offer flexibility. In closing, Python’s OOP equips developers with tools to create efficient and adaptable solutions.</p><p>A big thank you for taking the time to read this article! Your interest is much appreciated.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=761ad14b114e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>