<?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 Maisha Supritee Chowdhury on Medium]]></title>
        <description><![CDATA[Stories by Maisha Supritee Chowdhury on Medium]]></description>
        <link>https://medium.com/@maishaChow?source=rss-34a3913dfc05------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*1oqDZLzHcs_bgZpplG_fPg.jpeg</url>
            <title>Stories by Maisha Supritee Chowdhury on Medium</title>
            <link>https://medium.com/@maishaChow?source=rss-34a3913dfc05------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 17:07:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@maishaChow/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[How The Web Actually Works: The explanation I wish I got]]></title>
            <link>https://medium.com/@maishaChow/how-the-web-actually-works-the-explanation-i-wish-i-got-4f896c5f18a4?source=rss-34a3913dfc05------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f896c5f18a4</guid>
            <category><![CDATA[web]]></category>
            <category><![CDATA[clients]]></category>
            <category><![CDATA[browsers]]></category>
            <category><![CDATA[servers]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Maisha Supritee Chowdhury]]></dc:creator>
            <pubDate>Sat, 24 Jan 2026 02:01:24 GMT</pubDate>
            <atom:updated>2026-01-24T02:01:24.132Z</atom:updated>
            <content:encoded><![CDATA[<p>Ever wonder what actually happens when you open up a browser and type up a website like <a href="http://www.google.com/">www.google.com</a>? How do you actually land up in the google homepage? Is the browser a magic box which can pull up anything you write in it? Let’s dive under the hood of how a website actually works.</p><p>I’m going to use a lot of food and restaurant metaphors because that just makes it easier to understand. Plus, I love food.</p><h3>Client</h3><p>Anyways a <strong>client </strong>is basically the thing that is asking for something. We can think of a client as a customer at a restaurant, and the waiter is the browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EyW1xZxaEDsCdCpWfBVZoQ.jpeg" /></figure><h3>URL</h3><p>And what are we actually typing in a browser?</p><p>It usually looks something like <a href="http://www.whateverthenameofthewebsiteis.com./"><strong>http://www.whateverTheNameOfTheWebsiteIs.com.</strong></a></p><p>This is called a <strong>URL </strong>(<strong>Uniform Resource Locator</strong>). A URL is like a unique address for anything that exists on the web (page, image, video, etc) just like a house address. But for our example, we can think of it like a unique dish from the menu, no other dish on the menu can have the exact same name.</p><p>Let’s break this <strong>URL </strong>down into parts:</p><ul><li>The url starts with either http (Hyper Text Transfer Protocol) / https (Hyper Text Transfer Protocol Secure) which basically just decides how the data we send or receive should look like.</li><li><a href="http://www.whateverthenameofthewebsiteis.com/"><strong>www.whateverTheNameOfTheWebsiteIs.com</strong></a><strong> </strong>is the <strong>domain name</strong> aka the address. So if we were ordering a cheeseburger, www.cheeseburger.com is the domain name and we tell the waiter whether we want it given to us regularly (http) or with extra protection (https), because someone could easily steal our precious cheeseburger by the time it reaches our table right?</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hl0ldXnirNTYcRYp4Sl0jw.jpeg" /></figure><h3>IP Address</h3><p>But this URL is not the actual address where a website is stored at. It’s just the human friendly name for the address. Because the actual address a website is stored at looks something like 2801:4860:4860::8880, and is known as the <strong>IP address</strong>. Imagine having to remember so many random numbers for every website you want to visit. Sounds like a nightmare…</p><p>So how does the browser know that when we type <a href="http://www.whateverthenameofthewebsiteis.com/"><strong>www.whateverTheNameOfTheWebsiteIs.com</strong></a><strong> </strong>we actually want to go to the IP address 2801:4860:4860::8880?</p><h3>DNS</h3><p>The browser goes to something called the <strong>DNS(Domain Name System) </strong>server which is like a huge dictionary where each domain name is mapped to an IP address. This IP address is the address of the computer (server) that stores our website. So each food item on the menu at the restaurant is translated to some unique random numbers by our waiter. The waiter uses those numbers to choose which kitchen the cheeseburger will come from.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4iKYcHEMdRt7tNCQLyAVDA.jpeg" /></figure><h3>Server</h3><p>What is the server? A server is basically a computer somewhere in the world that stores websites, images, videos, etc. In our case we can think of the restaurant kitchen as the server, it stores the cheeseburger we requested using the waiter. So the browser sends a http/https request to the server to send the website to the client.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I7mSETy37Vka3Jv8sEw_FA.jpeg" /></figure><p>If the server has the website ready it sends back a status code of <strong><em>“200 OK”</em></strong>, which means the request was successful. So if the kitchen has the cheeseburger it confirms the waiter <strong><em>“Yes I will give you the cheeseburger now!”</em></strong> and then starts giving the cheeseburger to the waiter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JZyBFNJCenMHrlu-ox9XVA.jpeg" /></figure><h3>HTML, CSS and Javascript</h3><p>This response i.e. the website is actually a combination of HTML, CSS and Javascript files as well as any videos, images or other assets that the website might have:</p><ul><li><strong>HTML </strong>— the structure of the page<br>How the burger should be set up — where the bun goes, where the cheese slices go, etc.</li><li><strong>CSS</strong> — the style or appearance of the items on the page<br>What color the buns are, what color the sauce is, etc.</li><li><strong>Javascript</strong> — behavior of the elements on the page<br>What happens when we bite into the bun, what happens if the sauce slides off, etc.</li><li><strong>Images/Videos/Data </strong>— extra content on the page<br>The burger pick, sesame seeds on the bun, etc.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hbyb7PYn6MXHtEgttLa46A.jpeg" /></figure><p>Finally the browser (our waiter) builds/renders the website (sets up our cheeseburger on a plate nicely) into what we see on screen (our table).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EnM-vJuKakjlgjenBv3w-g.jpeg" /></figure><p>If the kitchen could not find/make the cheeseburger they would send back a <strong><em>“404 Error”</em></strong> message through our waiter to us. If the kitchen is very busy (too much traffic on the same server) or the kitchen is too far away (server is located geographically too far) we would be getting our food late (the website feels slow).</p><p>We also have different types of websites — static or dynamic.</p><ul><li><strong>Static</strong> — the server gives the browser a ready made page.<br>The kitchen gives us a fully cooked and prepared burger, served by the waiter.</li><li><strong>Dynamic </strong>— the server creates the page for us on the spot.<br>The burger is prepared right in front of us when we ask for it.</li></ul><h3>So to summarize:</h3><ul><li>We, the customers, are the clients.</li><li>The kitchen is the server.</li><li>We request a food item using its name such as cheeseburger (URL).</li><li>The waiter (browser) who takes our order (request) converts the cheeseburger name (URL) to the kitchen address which has the burger (IP address) using a big dictionary (DNS).</li><li>The waiter then requests the cheeseburger from the correct kitchen (server) — which they identified with the IP address.</li><li>If the kitchen has the cheeseburger and there are no problems, it sends an OK message to the waiter and then gives the cheeseburger to the waiter.</li><li>The waiter arranges the cheeseburger (the website) on a plate, garnishes it and serves it to us at our table (our screen).</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f896c5f18a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[In Laymen’s Terms IV: Arrays (CRUD and Storage)]]></title>
            <link>https://medium.com/@maishaChow/in-laymens-terms-iv-arrays-crud-and-storage-23d488253615?source=rss-34a3913dfc05------2</link>
            <guid isPermaLink="false">https://medium.com/p/23d488253615</guid>
            <category><![CDATA[storage]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Maisha Supritee Chowdhury]]></dc:creator>
            <pubDate>Sun, 14 Sep 2025 01:41:17 GMT</pubDate>
            <atom:updated>2025-09-22T09:42:04.048Z</atom:updated>
            <content:encoded><![CDATA[<p>Arrays, if thought of simply, are just lists. Most coding languages require the items in that “list” i.e. array to be of the same data type. Additionally, we must give the size or the number of elements that the array will have when we initialize it. This gives it the name <strong>“static” </strong>arrays as the size is fixed.</p><h3>Create</h3><p>For example we have a grocery list: eggs, bananas, tomatoes, milk. If we want to create this array of size 4 in code, it would look like:</p><p>C++:</p><pre>string groceries[4] = {&quot;eggs&quot;, &quot;bananas&quot;, &quot;tomatoes&quot;, &quot;milk&quot;};</pre><p>Java:</p><pre>String[] groceries = new String[4];<br>groceries[0] = &quot;eggs&quot;;<br>groceries[1] = &quot;bananas&quot;;<br>groceries[2] = &quot;tomatoes&quot;;<br>groceries[3] = &quot;milk&quot;;</pre><p>In the code above, first we make the array with its given size, then we are adding the elements in. However Java also allows us to make the array with specific elements and the size of the array gets automatically determined by the number of elements in it.</p><pre>String[] groceries = {&quot;eggs&quot;, &quot;bananas&quot;, &quot;tomatoes&quot;, &quot;milk&quot;};</pre><p>So can we store a number or a boolean value as an element in these arrays? The answer is no. The entire array needs to only be of the type of data we initialized it with.</p><p>But Python breaks this mold. In Python we use “lists” and lists can store different types of data as elements which technically makes them not arrays, but they are used interchangeably. Also, we don’t need to give the size of the list in Python — it can automatically detect the size.</p><p>Lists are <strong>“dynamic”</strong> which means we can keep adding or removing as many elements as we want, essentially growing/shrinking the size of the list at our will.</p><p>Python:</p><pre>groceryList = {&quot;eggs&quot;, 10, &quot;bananas&quot;, False, &quot;tomatoes&quot;, -3.456}<br>groceryList.append(&quot;milk&quot;)</pre><p>We can create dynamic arrays in C++ using vectors such as:</p><pre>vector&lt;string&gt; groceries = {&quot;eggs&quot;, &quot;bananas&quot;, &quot;tomatoes&quot;, &quot;milk&quot;};<br>groceries.push_back(&quot;cookies&quot;);</pre><p>Or in java using ArrayLists:</p><pre>ArrayList&lt;String&gt; groceries = new ArrayList&lt;&gt;();<br>groceries.add(&quot;eggs&quot;);<br>groceries.add(&quot;cookies&quot;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sp9X-h9SUJ1K6uF7PZ3QdA.jpeg" /></figure><h3>Read</h3><p>Unlike when we make a grocery list by hand and number the items on it starting from 1, arrays use a numbering system — also known as the index of an array — that starts from 0 to keep track of the elements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dMJCDbQ9JPys7zu-Y77HkA.jpeg" /></figure><p>So if we want to get the 3rd element from our array we do:</p><p><strong><em>groceries[2]</em></strong></p><p>How do we read through the entire array? There are multiple elements — 4 in our case, but we know that the positions of the elements always start at 0 and end at size of array — 1. Using this information we can simply loop through the array and read each element one at a time, increasing the index value at the end of each loop.</p><p>C++:</p><pre>int size = 4;<br>for(int i =0; i&lt;= size; i++){<br>  cout&lt;&lt; groceries[i] &lt;&lt; endl;<br>}</pre><p>Python:</p><pre>for i in range(len(groceries)):<br>  print(groceries[i])</pre><h3>Update</h3><p>Updating elements of an array is very simple — same as how we update any variable.</p><pre>groceries[1] = &quot;cookies&quot; # changes the 2nd item in our list from bananas to cookies</pre><h3>Delete</h3><p>To delete an element from a dynamic array:</p><p>Python:</p><pre>groceries.pop() #removes last element in array<br>groceries.pop(2) #removes element at index 2</pre><p>C++:</p><pre>groceries.erase(groceries.begin() + 2); //removes the element at index 2</pre><p>For static / fixed size arrays, removing an element requires a bit more work. If we want to remove the element at index 2, we just shift every element after (so from index 3 to the last index) one spot to the left so that the element at index 2 is overwritten by what was previously at index 3 and so on. If we have a size variable somewhere tracking the size of the array we also decrement it by 1.</p><p>So our groceries become: {“eggs”, “bananas”, “milk”, “milk”}. Our array is technically still of size 4, but our last element is just repeated in that extra slot of space. And when we use size to read through our array since we decremented it, we only read the array until the second last element giving the illusion that our array is of size 3: {“eggs”, “bananas”, “milk”}. We need to do this long process because we cannot shrink the size of static arrays.</p><h3>Storage</h3><p>But how are arrays actually stored in our computer memory under the hood?</p><p>When we create an array of size 4, the computer sees that we need 4 slots to store items and reserves a block of memory with enough space to store 4 items side by side. Whenever we store any data in memory, each of those slots have an address of their own — just like all of our houses have an address. So when we create an array, the computer always knows the “base address” i.e. the address of element at index 0, as well as the size of each element. Let’s take an integer array for example:</p><pre>int arr[5] = {10, 20, 30, 40, 50};</pre><p>A regular int is 4 bytes so each of the elements in arr is 4 bytes in size.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cUy9yCnViwD3j6ybSP-kuw.jpeg" /></figure><p>So when we want to get the 4th element in our array and we do<strong> arr[3],</strong> what the computer does is it calculates the address using the base address of our array along with the size of each element:</p><p>Address of 4th element:</p><blockquote>base address + (index * size of element)</blockquote><blockquote>So <strong>address = 2000 + (3*4) = 2012</strong></blockquote><p>And so it grabs whatever is stored in that memory address of 2012 and gives it back to us. This is true for both static and dynamic arrays.</p><p>But what about dynamic arrays — how can the computer predict and reserve a side by side block of 10 memory slots for our elements if we don’t tell it in advance we have 10 elements? And what happens when we add an 11th item? Dynamic arrays don’t just store the base address of the array, it stores details like:</p><ul><li>The current size of the array</li><li>How many elements can this array store i.e. the capacity</li><li>A pointer to the base address of the contiguous memory block (for C++) or a list of pointers to each of the objects in the array (for Python)</li></ul><p>Before you start panicking about what is a<strong> pointer </strong>— just think of it as a type of data which just stores addresses of other data.</p><p>So why do we need to store so many things for a dynamic array?</p><p>When we create a dynamic array for example arr = [10, 20, 30] the computer goes and stores the elements in that contiguous block of memory till it runs out of space. So for example, we now want to do add a new element (40) to arr, but there is no more space. The computer now assigns a new bigger block of memory (usually twice the original size), copies all the items from the array to this new block of memory, empties out the old block of memory and finally updates the pointer/pointers with the new address/addresses.</p><p>If we were to use static arrays and then need extra space to add new elements later down the line, we would have to follow the same process in our code.</p><ol><li>Make a new array with a bigger size — enough for our new elements</li><li>Copy the old items to the new array</li><li>Add the new elements</li><li>Delete the old array so the memory is freed</li></ol><p>But vectors, lists and ArrayLists just handle this entire process for us so we don’t have to do so much work and don’t have to worry about cleaning up!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23d488253615" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Step-by-Step: How to Unit Test your Next.js App with Jest and TypeScript]]></title>
            <link>https://medium.com/@maishaChow/step-by-step-how-to-unit-test-your-next-js-app-with-jest-and-typescript-24c610ef06a0?source=rss-34a3913dfc05------2</link>
            <guid isPermaLink="false">https://medium.com/p/24c610ef06a0</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[jest]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Maisha Supritee Chowdhury]]></dc:creator>
            <pubDate>Sun, 20 Jul 2025 23:44:35 GMT</pubDate>
            <atom:updated>2025-07-22T19:43:36.997Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bGsEDUgrSGXmNoYekuf3vA.png" /></figure><p>I recently started learning to test React + NextJS applications that use TypeScript with Jest, but unfortunately it was quite difficult to find a unified, step by step guide for configuring jest and react testing library for TypeScript. So, of course I took matters into my own hands and after piecing everything together (and breaking it a few times), I’ve put together a step-by-step guide to help you get Jest and React Testing Library running smoothly with TypeScript. Plus I get into some basic unit tests to get you up and running in no time! If you’re tired of jumping between tabs and Stack Overflow threads, this one’s for you.</p><p>PS This is just how I set up Jest for my projects, feel free to adjust it according to your own preferences.</p><h3>Installation and Setup</h3><h4>Installing dependencies</h4><p>Go inside of your NextJs React project and open up the terminal. Use the following command to install all dependencies needed:</p><pre>npm install --save-dev jest jest-environment-jsdom @types/jest @testing-library/react @testing-library/jest-dom @testing-library/dom @testing-library/user-event ts-node ts-jest @jest/globals</pre><h4>Config and Setup Files</h4><p>Next in your main project directory create a <strong><em>jest.config.js</em></strong> file:</p><pre>// eslint-disable-next-line @typescript-eslint/no-require-imports<br>const nextJest = require(&quot;next/jest&quot;);<br><br>const createJestConfig = nextJest({<br>  // Provide the path to your Next.js app to load next.config.js and .env files<br>  dir: &quot;./&quot;,<br>});<br><br>// Add any custom config to be passed to Jest<br>const customJestConfig = {<br>  setupFilesAfterEnv: [&quot;&lt;rootDir&gt;/jest.setup.ts&quot;],<br>  testEnvironment: &quot;jest-environment-jsdom&quot;,<br>  moduleNameMapper: {<br>    // Handle module aliases<br>    &quot;^@/(.*)$&quot;: &quot;&lt;rootDir&gt;/$1&quot;,<br>  },<br>  collectCoverage: true,<br>  collectCoverageFrom: [<br>    &quot;app/**/*.{js,jsx,ts,tsx}&quot;,<br>    &quot;src/**/*.{js,jsx,ts,tsx}&quot;,<br>    &quot;!**/*.d.ts&quot;,<br>    &quot;!**/node_modules/**&quot;,<br>    &quot;!**/vendor/**&quot;,<br>  ],<br>  coverageDirectory: &quot;coverage&quot;,<br>  coveragePathIgnorePatterns: [<br>    &quot;/node_modules/&quot;,<br>    &quot;/coverage&quot;,<br>    &quot;package.json&quot;,<br>    &quot;package-lock.json&quot;,<br>    &quot;reportWebVitals.ts&quot;,<br>    &quot;setup.ts&quot;,<br>    &quot;index.tsx&quot;,<br>  ],<br>  testPathIgnorePatterns: [&quot;&lt;rootDir&gt;/.next/&quot;, &quot;&lt;rootDir&gt;/node_modules/&quot;],<br>};<br><br>// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async<br>module.exports = createJestConfig(customJestConfig);</pre><p>Then create a<strong><em> jest.setup.ts</em></strong> file: (This will usually contain mocks)</p><pre>// //jest-dom adds custom jest matchers for asserting on DOM nodes.<br>// allows you to do things like:<br>// expect(element).toHaveTextContent(/react/i)<br>import &quot;@testing-library/jest-dom&quot;;</pre><h4>Additional code for preexisting files</h4><p>Add the following in your <strong><em>tsconfig.json</em></strong> file:</p><p>Add the types in the <strong>compiler options</strong>:</p><pre>&quot;compilerOptions&quot;: {<br>&quot;types&quot;: [&quot;jest&quot;, &quot;@testing-library/jest-dom&quot;, &quot;node&quot;],<br>}</pre><p>Add these include patterns into your existing <strong>include</strong>:</p><pre>&quot;include&quot;: [&quot;**/*.test.ts&quot;,<br>&quot;**/*.test.tsx&quot;,<br>&quot;jest.config.js&quot;]</pre><p>And finally add the following scripts to your <strong><em>package.json</em></strong>:</p><pre>&quot;scripts&quot;: {<br>&quot;test&quot;: &quot;jest&quot;,<br>&quot;test:watch&quot;: &quot;jest - watch&quot;,<br>&quot;test:coverage&quot;: &quot;jest - coverage&quot;<br>}</pre><p>Now let’s get to actually writing some tests!</p><h3>Unit Tests</h3><p>Before we start writing our first test, let’s actually understand what a unit test is.</p><p>Simply speaking, when you want to test a single component or element in your app, or maybe even just a single function by itself, you use a<strong> unit test</strong>. So they are the smallest tests to verify if a single function or piece of code is working the way you expect it to. You use these tests on elements that don’t rely on any external dependency such as databases, api calls, and so on. You just want to ensure that your code works well by itself in isolation, and to do that we use unit tests.</p><p>For a unit test, you already know what the inputs are for your test and what the expected outputs look like, so you assert whether the actual output of your code matches your expected output or not.</p><p>I’ve created a very basic React + NextJS app using TypeScript and TailwindCSS for our example.</p><p>Find the public repository for this project at:</p><p><a href="https://github.com/maishaSupritee/test-jest-app">GitHub - maishaSupritee/test-jest-app</a></p><p>The app has one page with 2 components.</p><p><strong>The main component:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6vtKoN4bAAqghxx8" /></figure><p>We have some basic texts, one image, a link that opens up a new window and a button which scrolls you to the next section of the page when clicked.</p><p><strong>Secondary component:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*85KviWxDC7UJUore" /></figure><p>If we scroll down we see our secondary component, which just displays a click me button that appears every 3 seconds and disappears after 3 seconds. Clicking on the button creates an alert on our screen which displays “Button Clicked”.</p><p>I like to write all my tests in a separate directory called tests and then for each component have a <strong><em>myComponent.test.tsx</em></strong> file. So create a tests folder in your base project directory and create a <strong>main.test.tsx</strong> file inside.</p><p>The basic structure of a unit test using jest can be like this:</p><pre>test(&quot;description of what the test is going to do&quot;, () =&gt; {<br>  // ARRANGE -&gt; set up variables and objects, any initial conditions we need to test our component<br>  <br>  //ACT -&gt; actually implement the component/code we want to test, for example function calls<br>  <br>  //ASSERT -&gt; verify whether the code being tested produced an output that matches our expected output from that code. If it matches, the test passes, or else it fails<br>});</pre><h3>Main component tests</h3><p>The first test we will write is a snapshot test.</p><h4>Snapshot Test</h4><p>Everything in our main component is static, it will not change regardless of what we do when the component is open on our page. So it’s perfect for a snapshot test, as we don’t expect any unexpected UI changes.</p><p>For a snapshot test we render the UI component, main in our case, and take a snapshot and then compare it with a previous original snapshot we had saved as reference.</p><p><strong><em>main.test.tsx:</em></strong></p><pre>import Main from &quot;@/app/components/main&quot;;<br>import { render } from &quot;@testing-library/react&quot;;<br><br>test(&quot;main component matches snapshot&quot;, () =&gt; {<br>  const { asFragment } = render(&lt;Main /&gt;);<br>  expect(asFragment()).toMatchSnapshot();<br>});</pre><p>The render function from react-testing-library gives us many different options to use with it, <strong>asFragment</strong> being one of them. <strong>asFragment</strong> gives us a static representation of the rendered DOM, so we can use it to compare against our snapshot.</p><ul><li>So our const { asFragment } = render(&lt;Main /&gt;); is working as both our ARRANGE and ACT stage, setting up the asFragment and also calling our Main function.</li><li>expect(asFragment()).toMatchSnapshot(); is our ASSERT stage, where we are saying we “expect” our rendered fragment to match our snapshot.</li></ul><h3>Running tests</h3><p>To run all tests. In the terminal just do:</p><pre>npm test</pre><p>To run a specific test file do:</p><pre>npm test myComponent.test.tsx</pre><p>So to run our snapshot test we do:</p><pre>npm test main.test.tsx</pre><p>This gives us the following result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/0*udgtpjWQ7k5SLoSQ" /></figure><p>Jest gives us a very comprehensive test report with information such as whether our test passed or not, as well as detailed coverage by file. Pretty neat, yes?</p><p>If you, however, don’t need all the extra information about coverage, you can simply remove this bit of your customJestConfig in the <strong><em>jest.config.js</em></strong> file:</p><pre>collectCoverageFrom: [<br>  &quot;app/**/*.{js,jsx,ts,tsx}&quot;,<br>  &quot;src/**/*.{js,jsx,ts,tsx}&quot;,<br>  &quot;!**/*.d.ts&quot;,<br>  &quot;!**/node_modules/**&quot;,<br>  &quot;!**/vendor/**&quot;,<br>],<br>coverageDirectory: &quot;coverage&quot;,<br>coveragePathIgnorePatterns: [<br>  &quot;/node_modules/&quot;,<br>  &quot;/coverage&quot;,<br>  &quot;package.json&quot;,<br>  &quot;package-lock.json&quot;,<br>  &quot;reportWebVitals.ts&quot;,<br>  &quot;setup.ts&quot;,<br>  &quot;index.tsx&quot;,<br>],</pre><p>Remove the above lines of code and change the value of the <strong>collectCoverage</strong> field to false. So your new customJestConfig looks like this:</p><pre>// Add any custom config to be passed to Jest<br>const customJestConfig = {<br>  setupFilesAfterEnv: [&quot;&lt;rootDir&gt;/jest.setup.ts&quot;],<br>  testEnvironment: &quot;jest-environment-jsdom&quot;,<br>  moduleNameMapper: {<br>    // Handle module aliases<br>    &quot;^@/(.*)$&quot;: &quot;&lt;rootDir&gt;/$1&quot;,<br>  },<br>  collectCoverage: false,<br><br>  testPathIgnorePatterns: [&quot;&lt;rootDir&gt;/.next/&quot;, &quot;&lt;rootDir&gt;/node_modules/&quot;],<br>};</pre><p>And now if you run your test again, this is all you get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/0*3MsgGg1kb0YevFnc" /></figure><p>But this is a case where your test passes. Let’s try to make our snapshot test fail and see what happens.</p><p>So if we go ahead and change even just the header text in our main component from <strong>“Jest Testing” </strong>to <strong>“Jest Test”</strong> and then rerun our test, our test fails:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/0*bXJsXEKXcEhUQkrQ" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*s0rj1EHxVYQtZtZf" /></figure><p>What’s cool is that not only do you know your test failed, but it also tells you which specific line of code made your test fail. As you can see the test was expecting “Jest Testing” because that was in our original snapshot we were using to reference and compare with our rendered page. But once we changed our code, we didn’t update the snapshot we are using yet and so the test fails even though “Jest Test” is what we want to have.</p><p>So let’s update our snapshot:</p><pre>npm test - -u</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/0*_q4ZrGWklVoakaIX" /></figure><p>Now our reference snapshot is updated to match our UI change, and the test passes successfully.</p><p>Ok you have now successfully set up a React + NextJs + TypeScript project with jest, written your first test, ran it, passed and failed the test!</p><p>Moving on…</p><h4>Testing text, buttons, images and links</h4><p>Now let’s get started with some simple unit tests to test the basic functionality of our component.</p><p>There are multiple ways you can access the different elements such as text, buttons, links, etc on your screen. So I’m going to use a couple of different ones for the elements in our main.</p><p><strong><em>main.test.tsx:</em></strong></p><pre>test(&quot;all static elements are rendered correctly&quot;, () =&gt; {<br>  render(&lt;Main /&gt;);<br>  const header = screen.getByRole(&quot;heading&quot;, { name: /jest test/i });<br>  const description = screen.getByText(/Let&#39;s try writing some unit tests!/i);<br>  const image = screen.getByAltText(&quot;Test Image&quot;);<br><br>  expect(header).toBeInTheDocument();<br>  expect(description).toBeInTheDocument();<br>  expect(image).toBeInTheDocument();<br>});</pre><p>We render the main component first. Then we are getting each of the elements separately from our rendered screen.</p><ul><li>getByRole -&gt; as the name suggests we get the element that matches the role we provide. There are many roles provided to us, all for different HTML elements, such as heading, paragraph, link, img, and more. We are getting our h1 element by its role, “heading”, and its name i.e. the text the heading has inside.</li><li>getByText -&gt; probably the simplest one, it gets the element whose text matches the text we provide.</li><li>getByAltText -&gt; getting the image element that has the alt text we provide.</li></ul><p>Once we have all of our elements, we are asserting whether they exist in our page or not by doing:</p><blockquote><strong>expect(element).toBeInTheDocument();</strong></blockquote><p>All this does is checks whether all the elements we want to exist in our page actually exist or not.</p><p>This makes more sense for our static elements like headers, descriptions, and images. For our link on the other hand, we want it to open up the provided link on a separate tab when we click on it. So let’s test whether the link does that or not.</p><p>We can create a new test for our link and button components:</p><pre>test(&quot;test button and link elements work properly&quot;, () =&gt; {<br>  render(&lt;Main /&gt;);<br><br>  const link = screen.getByTestId(&quot;pexels-link&quot;);<br>  const button = screen.getByRole(&quot;button&quot;, {<br>    name: /go to secondary section/i,<br>  });<br>  const buttonLink = button.querySelector(&quot;a&quot;);<br><br>  expect(link).toBeInTheDocument();<br>  window.open = jest.fn(); // Mock window.open to prevent actual navigation<br>  link.click();<br>  expect(window.open).toHaveBeenCalledWith(<br>    &quot;https://www.pexels.com/photo/time-displayed-on-top-of-a-building-1824273/&quot;,<br>    &quot;_blank&quot;<br>  );<br><br>  expect(button).toBeInTheDocument();<br>  expect(buttonLink).toHaveAttribute(&quot;href&quot;, &quot;#secondary&quot;);<br>});</pre><p>Similar to our previous test, we start by rendering the component and getting the link and button elements. We can simply get the link by either getByRole of “link” or by using getByText(“pexels”) but I wanted to show a special getBy option known as <strong>getByTestId.</strong></p><p>What if we don’t have simple html elements in our app such as a button, paragraph, link, img, etc? What if we have some element that is dynamically created, has no clear text content or is difficult to locate by using simpler, more straightforward gets like getByRole/getByText?</p><p>For elements that fall in those categories, you can add a<strong> data-testid</strong> field to the element. For example for our link element, this would look like:</p><pre> &lt;Link<br>    href=&quot;https://www.pexels.com/photo/time-displayed-on-top-of-a-building-1824273/&quot;<br>    className=&quot;text-blue-500 hover:underline ml-2&quot;<br>    data-testid=&quot;pexels-link&quot;<br>    onClick={(e) =&gt; {<br>      e.preventDefault();<br>      window.open(<br>         &quot;https://www.pexels.com/photo/time-displayed-on-top-of-a-building-1824273/&quot;,<br>          &quot;_blank&quot;<br>      );<br>    }}<br>  &gt;<br>  pexels<br>  &lt;/Link&gt;</pre><blockquote>DO NOT OVER USE TESTID. USE IT ONLY IN SITUATIONS WHERE YOU HAVE NO OTHER WAY TO GET AN ELEMENT IN YOUR PAGE.</blockquote><p>I’m only using it for this simple link element to show its usage but you can easily get links such as the above with getByText.</p><p>We are also getting the link inside of our button element by querying for the html anchor <strong>“a”</strong> inside of it.</p><p>Once we are sure the link exists, we try to test what happens upon clicking it.</p><p>The <strong>window.open = jest.fn()</strong> mimics how the browser opens up a new window, without actually performing the action. Why do we do this?</p><p>Because we don’t want to actually open up an external window during our unit test, we want to keep our tests isolated and only test the core logic.</p><p>Next we simulate a user clicking on our link using <strong>link.click().</strong></p><p>Finally we verify whether clicking the link opens up the link we expect, AND whether it was called with <strong>“_blank”</strong> as the second parameter which opens up the link in a new window.</p><p>We also check whether the button exists in our page, and whether the link within the button has the attribute <strong>“href”</strong> and its value is <strong>“#secondary”.</strong> This is different from the previous link we checked as this one is just navigating to a different section of our website.</p><p>That’s all for our main component so let’s move onto the secondary component which is a bit more interesting!</p><h3>Secondary component tests</h3><p>So our secondary component only has a single button which appears every 3 seconds. But how do we mimic this behaviour of 3 seconds passing in our test?</p><p>We don’t actually want to wait for 3 seconds and then test if it appears, wait another 3 seconds to check if it disappears and so on.</p><p>Instead we can use a fake timer provided to us by Jest.</p><p><strong><em>secondary.test.tsx:</em></strong></p><pre>import Secondary from &quot;@/app/components/secondary&quot;;<br>import { render, screen, act } from &quot;@testing-library/react&quot;;<br><br>// Mock timers for controlling setInterval<br>jest.useFakeTimers();<br><br>afterEach(() =&gt; {<br>  jest.clearAllTimers();<br>});</pre><p>So we start off by calling fake timers, and we use the <strong>afterEach()</strong> function to reset and clear all timers after each of our tests in this test suite.</p><h4>Testing visibility of button</h4><pre>test(&quot;button toggles visibility every 3 seconds&quot;, () =&gt; {<br>  render(&lt;Secondary /&gt;);<br><br>  // initially visible<br>  expect(<br>    screen.getByRole(&quot;button&quot;, { name: /click me!/i })<br>  ).toBeInTheDocument();<br><br>  //after 3 seconds - hidden<br>  act(() =&gt; {<br>    jest.advanceTimersByTime(3000);<br>  });<br>  expect(<br>    screen.queryByRole(&quot;button&quot;, { name: /click me!/i })<br>  ).not.toBeInTheDocument();<br><br>  // after another 3 seconds - visible again<br>  act(() =&gt; {<br>    jest.advanceTimersByTime(3000);<br>  });<br>  expect(<br>    screen.getByRole(&quot;button&quot;, { name: /click me!/i })<br>  ).toBeInTheDocument();<br><br>  // after another 3 seconds - hidden again<br>  act(() =&gt; {<br>    jest.advanceTimersByTime(3000);<br>  });<br>  expect(<br>    screen.queryByRole(&quot;button&quot;, { name: /click me!/i })<br>  ).not.toBeInTheDocument();<br>});</pre><p>At first we render our secondary component. Next, instead of storing the button in our screen in a variable and then asserting if it exists or not, we are just directly combining the two steps into one.</p><p>Now what’s interesting is — notice how we used <strong>getByRole</strong> to get our button whenever it is <strong>visible</strong> and we are using <strong>queryByRole</strong> whenever we want to check if the button is <strong>invisible</strong>.</p><p><strong>Difference between get and query</strong></p><ul><li>When we use get to get one of the elements from our page, if it doesn’t exist our test will immediately fail.</li><li>On the other hand, query will try to find the element in our page and if it doesn’t exist it will return null, so our test will not fail.</li></ul><p>That’s why we are using get when the button is visible on our screen, while we use query for when it’s invisible. If we used get for the invisible case then the test would fail, but we want to verify that the button is invisible and that is the expected behaviour so it shouldn’t fail our test.</p><p>In the case of our button, it’s changing states from visible to invisible every 3 seconds. So when we are advancing our timer to mimic 3 seconds passing in our test, we need to wrap it in the <strong>act()</strong> function from react’s testing-library. This is because whenever there is a state update, react needs to rerender. So what <strong>act() </strong>does is it makes sure that the state update is processed and the component rerenders before we continue with our test. Because if we try to “assert” or “verify” the visibility status of our button before it has actually finished updating its state, then we can either get:</p><ul><li>Flaky tests -&gt; the test is successful sometimes, and unsuccessful other times</li><li>Race conditions -&gt; trying to test or assert before our DOM has finished updating</li></ul><h4>Testing alert</h4><pre>test(&quot;button click creates an alert&quot;, () =&gt; {<br>  window.alert = jest.fn(); // Mock the alert function<br>  render(&lt;Secondary /&gt;);<br><br>  const button = screen.getByRole(&quot;button&quot;, { name: /click me!/i });<br>  button.click();<br>  expect(window.alert).toHaveBeenCalledWith(&quot;Button clicked!&quot;);<br>  expect(window.alert).toHaveBeenCalledTimes(1);<br>});</pre><p>We first create a mock of our alert function, render our secondary component and then get the button. We simulate clicking on the button, and then expect our alert to have the “button clicked!” text and only be called once.</p><h4>Testing button styles</h4><p>The final and most simple test we can do is, testing whether the button matches the exact styles we want it to have:</p><pre>test(&quot;button has correct styles&quot;, () =&gt; {<br>  render(&lt;Secondary /&gt;);<br><br>  const button = screen.getByRole(&quot;button&quot;, { name: /click me!/i });<br>  expect(button).toHaveClass(<br>    &quot;px-6&quot;,<br>    &quot;py-3&quot;,<br>    &quot;bg-purple-500&quot;,<br>    &quot;text-white&quot;,<br>    &quot;rounded-lg&quot;,<br>    &quot;hover:bg-purple-600&quot;,<br>    &quot;transition-colors&quot;,<br>    &quot;duration-200&quot;<br>  );<br>});</pre><p>We are simply asserting whether the button has matching classes for its styles as the ones we expect it to have.</p><p>Finally, remember to run your test with:</p><pre>npm test secondary.test.tsx</pre><p>Or run all your tests:</p><pre>npm test</pre><p>Of course this is only the tip of the iceberg when it comes to testing react components, but I hope this is enough to get everyone up and going!</p><p>Project repository: <a href="https://github.com/maishaSupritee/test-jest-app"><strong>https://github.com/maishaSupritee/test-jest-app</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24c610ef06a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Git: the only commands you’ll ever really need]]></title>
            <link>https://medium.com/@maishaChow/git-the-only-commands-youll-ever-really-need-b25b411da6a9?source=rss-34a3913dfc05------2</link>
            <guid isPermaLink="false">https://medium.com/p/b25b411da6a9</guid>
            <category><![CDATA[command-line]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[terminal]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[github]]></category>
            <dc:creator><![CDATA[Maisha Supritee Chowdhury]]></dc:creator>
            <pubDate>Tue, 25 Mar 2025 03:56:21 GMT</pubDate>
            <atom:updated>2025-03-25T03:57:12.564Z</atom:updated>
            <content:encoded><![CDATA[<p>I’m compiling a list of essential Git commands that I use daily — or at least frequently — because, let’s be honest, we all tend to forget even the simplest commands sometimes. After all, we’re only human! So, here’s a collection of the Git commands you’ll actually need and use.</p><h3>Configuring Git</h3><p>Global config settings are applicable for all repositories you work with on that computer. Make sure to use the same username and email as your git account.</p><p>To configure the user name associated with your git:</p><pre>git config --global user.name &quot;userName&quot;</pre><p>To configure the email associated with your git:</p><pre>git config --global user.email youremail@example.com</pre><p>To sign all commits for all repositories on our computer:</p><pre>git config --global commit.gpgsign true</pre><p>To see the list of global git config settings you have set up:</p><pre>git config --global --list</pre><p>But for specific repositories if you want to change the associated email or username for your commits, you can change git config settings on the local level.</p><p>Navigate into the directory of the git repository for which you want to specifically change the config settings:</p><pre>git config --local user.name “userName”<br>git config --local user.email personalemail@example.com<br>git config commit.gpgsign true<br>git config –local –list</pre><h3>Initializing Git</h3><p>If we already have a folder in which we would like to use git, navigate into the folder:</p><pre>git init</pre><p>To check which files have been updated, added, or deleted in our current working directory, either untracked or staged:</p><pre>git status</pre><h3>Cloning</h3><p>To get a repository that already exists on git copied down in your local computer using SSH:</p><pre>git clone git@github.com:username/repository.git</pre><h3>Staging</h3><p>To track changes in a specific file, i.e. staging the file once we are ready to commit/store to our repository:</p><pre>git add filename</pre><p>To stage all files from our current working directory:</p><pre>git add .</pre><p>To undo a git add i.e. move the changes out of the staging area:</p><pre>git restore --staged filename</pre><h3>Commit</h3><p>To save your staged files to your git repository, commit them with:</p><pre>git commit -m &quot;message&quot;</pre><p>To sign your commit:</p><pre>git commit -S -m &quot;message&quot;</pre><h3>Branches</h3><p>To create a new branch from the branch you currently are in:</p><pre>git branch branch-name</pre><p>To create a new branch and switch over to your new branch:</p><pre>git checkout -b branch-name</pre><p>See the list of your branches:</p><pre>git branch</pre><p>To switch branches:</p><pre>git checkout branch-name</pre><p>To set up your remote repository so it tracks or has a copy of your local branch as well:</p><pre>git push --set-upstream origin branch-name</pre><p>To delete a local branch:</p><pre>git branch -d branch-name</pre><p>To delete a branch in the remote repository:</p><pre>git push origin -d branch-name</pre><h3>Push</h3><p>To finally upload all your changed files to your remote git repository, push them:</p><pre>git push</pre><p>To upload a specific branch to the remote repository, navigate into the branch and:</p><pre>git push origin branch-name</pre><h3>Updating Local Repository</h3><p>To update your local repository so it fetches all changes made to the remote repository:</p><pre>git fetch</pre><p>But we are not done yet, we have only downloaded the new commits from our remote but not updated our local clone yet. For this we do:</p><pre>git merge</pre><p>We could also do rebase instead of merge. More on merging and rebasing later.</p><p>However, both merging and rebasing will create new commits in our history so instead, we can also do the above two steps in just one go using:</p><pre>git pull</pre><p><strong>git pull</strong> is basically a combination of git fetch and git merge, where git fetch downloads all the changes from the remote repository and git merge actually combines them into your local repository.</p><p>To fetch changes from a specific remote repository, not the one your local one is currently tracking, create a new branch and within this new branch:</p><pre>git pull git@github.com:username/repository-name.git branch-name</pre><p>The branch-name mentioned in the above command is the remote branch you want to track.</p><h3>Merging</h3><p>To merge one branch into another, first checkout the branch you want to merge into:</p><pre>git checkout branch1</pre><p>Now we merge the branch we want to into this branch we are currently in, i.e. branch2 gets merged into branch1:</p><pre>git merge branch2</pre><p>Now if you get the super scary merge conflicts, but you don’t have the time to deal with them right now, fear not, you can abort your merge:</p><pre>git merge –abort</pre><h4>Merge Conflicts</h4><p>But let’s get to actually solving the merge conflicts. After doing git merge and getting merge conflicts, we can do <strong>git status</strong> to see which files have conflicts and which don’t.</p><p>For example:</p><p>We tried to merge test branch into main branch resulting in conflicts:</p><pre>git checkout main<br>git merge test</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/0*sOeD-BUSmK9xfysg" /></figure><pre>git status</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/0*FHPEgCX0kGqC11Gh" /></figure><p>This tells us that we have a conflict in our README.md file.</p><p>We can also check which commits are resulting in a conflict:</p><pre>git log --merge --oneline</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/0*OaQ5AVhIdW8Ld_c8" /></figure><p>So we know the conflicts arising from changes made in the<em> “Update main”</em> commit of main branch, and the <em>“Testing merge”</em> commit of the test branch.</p><p>Now we need to open the file with the conflicts in a text editor. I’m opening mine in VSCode, but regardless of which editor you use, git will include these conflict markers<strong> &lt;&lt;&lt;&lt;&lt;&lt;&lt;, ======, &gt;&gt;&gt;&gt;&gt;</strong>, in the spots it couldn’t merge automatically.</p><p>Any code between <strong>&lt;&lt;&lt;&lt;&lt;&lt;&lt; HEAD and =====,</strong> is code added by the main branch.</p><p>While any code between <strong>====== and &gt;&gt;&gt;&gt;&gt;&gt;</strong>, is code added by our feature branch (test).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oF4efxOZE9_w2ihF" /></figure><p>So the main branch had <em>“Testing mergeConflict”</em> while the test branch was trying to write <em>“Testing merge”</em> to the same line, giving us a conflict.</p><ul><li><strong>Accept Current Change</strong> — results in <em>“Testing mergeConflict”</em></li><li><strong>Accept Incoming Change</strong> — results in <em>“Testing merge”</em></li><li><strong>Accept Both Changes</strong> — results in <em>“Testing mergeConflict”</em> in one line and “Testing merge” in the next line</li><li>Or you could choose to manually fix the conflict by rewriting that line of code to suit your needs</li></ul><p>After we are done fixing our merge conflicts, we need to stage the file again:</p><pre>git add README.md</pre><p>And then commit and push to our remote repository:</p><pre>git commit -m &quot;Merge test into main&quot;<br>git push</pre><h3>Squash commits</h3><p>Imagine our test branch has a lot of commits but we want to just merge all of the changes into our main branch with one commit to keep our git history looking clean. Then we can squash all the commits in test branch when we are merging it in:</p><pre>git merge --squash test</pre><p>We can get merge conflicts which we now know how to fix, and if all is good we commit:</p><pre>git commit</pre><p>This will open up your commit message in your text editor, allowing you to modify it. By default it contains all your previous commit messages of the commits you squashed which you can choose to keep, or you can edit and just have a single message.</p><p>If you don’t want any of those commit messages and want just a single new commit message, you could also do this easily by:</p><pre>git commit -am &quot;Single message for all the commits I squashed like bugs&quot;</pre><h4>Beware we are entering risky territories now. Proceed with caution…You’ve been warned!</h4><h3>Rebase</h3><p>Rebasing is used to create a cleaner, more linear project history by moving or combining commits. While it helps avoid unnecessary merge commits, it’s important to use rebase carefully — because it <strong><em>rewrites commit history,</em></strong> it can introduce issues, especially when working in a shared repository. If you rebase after pushing changes that others have based work on, it can cause conflicts and confusion.</p><p>To safely use rebase, it’s best to do it<strong> before pushing</strong> your branch to the remote repository.</p><p>For example:</p><ul><li>We have a main branch with one commit: <em>update readme.</em></li><li>We create a new branch called feature from main, and add one commit to it: <em>update feature.</em></li><li>Meanwhile someone adds another commit to main: <em>update main.</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rPJ_0Y0am4Cf2p3E" /></figure><p>Now, the feature branch is one commit ahead (its own change) and one commit behind (main has a new change). To integrate the latest changes from main into feature with a clean history, we rebase:</p><pre>git checkout -b feature<br>git rebase main</pre><p>What happens during rebase?</p><ul><li>Git temporarily removes our local commits from feature (i.e. update feature).</li><li>It fast-forwards feature to the tip of main (after update main).</li><li>Git then reapplies our original commits, one by one, on top of the updated base.</li></ul><p>If there are no conflicts, this process completes smoothly. If there are any merge conflicts, open in a text editor like VSCode to fix them and then close the file.</p><pre>git add filename<br>git rebase --continue</pre><p>This will open up each rebased commit message in the text editor for us to edit if we want.</p><p>When Git reapplies our original commits from feature after rebasing to main, it may encounter new merge conflicts — even within the feature branch itself — which might result in:</p><ul><li>A conflict that needs manual resolution.</li><li>A potential merge commit, even though rebasing typically avoids them.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UV_RwmcuXWi4ONwQ" /></figure><p>Another way to rebase is to use the interactive mode:</p><pre>git rebase --interactive main</pre><p>This will open up the text editor for us to select which commits to:</p><ul><li><strong>pick</strong> (keep the commit as-is)</li><li><strong>squash</strong> (combine it with the commit above)</li><li><strong>drop</strong> (remove the commit)</li><li><strong>reword</strong> (edit the commit message) and more</li></ul><h3>Undo</h3><p>We are humans and so we make mistakes quite often. What happens if we created a git commit but we need to undo it? Depends on whether we pushed the commit to the remote repository yet or not.</p><p>First we need to check if we have pushed a commit yet or not:</p><pre>git log --oneline --branches --not --remotes</pre><p>If the commit we want to undo shows up when we write this command, then we have not pushed the commit yet.</p><p>For example:</p><p>We’ve created a branch from main, called undo. In this branch we create a commit called <em>“unpushed commit”</em>. Once we run <strong>git log –oneline –branches –not –remotes:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/0*_XvXwXMXPqC8OQHm" /></figure><p>So our commit<em> “unpushed commit”</em> in the branch undo has not been pushed to the remote repository yet. This means we can do a git reset to get rid of this commit.</p><h4>Git reset</h4><p>When we do git reset on a commit that hasn’t been pushed to our remote repository yet, git completely gets rid of that commit from history as if it never even existed.</p><p>So to remove just the latest commit we can do:</p><pre>git reset HEAD~1</pre><p>This removes our <em>“unpushed commit”</em> from the history but leaves the changes we made in that commit in our working copy as <strong>uncommitted changes.</strong></p><p><strong>HEAD </strong>is just the name of the current commit your git is checked out at. And by doing ~1 we are deleting just that one commit, but we can choose how many commits to delete.</p><p>For example to delete last 4 commits:</p><pre>git reset HEAD~4</pre><p>Now we have 2 choices:</p><ol><li>Make more changes in that file and commit it again.</li><li>do : <strong>git checkout . </strong><br>This will remove all those uncommitted changes COMPLETELY from our file.</li></ol><h4>Git revert</h4><p>Now let’s create another commit in our <strong>“undo”</strong> branch called <strong><em>“pushed commit”</em></strong> and then actually push this commit to our remote repository. So how do we undo this pushed commit?</p><p>Let’s do:</p><pre>git log --oneline</pre><p>This will list all our commits with their hashes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/0*rUyi2OffwB6xO83P" /></figure><p>To undo this<em> “pushed commit” </em>we do:</p><pre>git revert --no-edit f18ca47</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/0*svmzkAPZKy40qgXV" /></figure><p>So using revert doesn’t simply delete our old <em>“pushed commit” </em>but creates a new commit <strong>(<em>Revert “pushed commit”</em></strong>) that reverses the changes made in <em>“pushed commit”</em>. Adding the<strong> –no-edit</strong> flag allows us to just use the default commit message instead of having to write one ourselves.</p><p>Finally we can just push this commit to our remote repository with:</p><pre>git push origin undo</pre><p>Git revert is powerful as we can even delete/undo changes made by past commits and not only the most recent one.</p><p>Let’s add a few commits to our undo branch —<em> “update1”, “update2”</em> and <em>“update3”.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/0*_oTDE2qMvVgiQY8w" /></figure><p>Let’s say we wish to revert changes made in update2 but still keep everything before and after it intact.</p><pre>git revert --no-edit bd74668</pre><p>We might even run into merge conflicts when reverting old commits, so after fixing those conflicts with our text editor:</p><pre>git add filename<br>git revert --continue<br>git push</pre><p>Since git revert doesn’t modify the original commit like git reset does, it’s a safer option, though it may add extra commits to your history.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b25b411da6a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[useEffect vs useQuery: Simplifying Data Fetching in React]]></title>
            <link>https://medium.com/@maishaChow/useeffect-vs-usequery-simplifying-data-fetching-in-react-87f9ef9012e5?source=rss-34a3913dfc05------2</link>
            <guid isPermaLink="false">https://medium.com/p/87f9ef9012e5</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[usequery]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[useeffect]]></category>
            <dc:creator><![CDATA[Maisha Supritee Chowdhury]]></dc:creator>
            <pubDate>Thu, 06 Mar 2025 03:15:37 GMT</pubDate>
            <atom:updated>2025-03-06T04:22:47.565Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XJQPYIsbpdrHNQ3U32xDmg.jpeg" /></figure><p>When building React applications, one task we all face at one point or another is fetching data from some external API. Like many beginners — including myself until recently — I initially used the useEffect hook from React to manually manage data fetching, state updates, and handling loading and error states. But as an application starts getting bigger in size, the useEffect hook can no longer satisfy all our needs. Fortunately, we have a powerful solution at our disposal: the useQuery hook from TanStack Query (formerly React Query), a game-changer that simplifies data fetching and state management with ease.</p><p>useEffect is like cooking a meal by yourself.</p><ul><li>You have to get the ingredients from the grocery i.e. <strong>set up state variables</strong></li><li>Follow a recipe i.e.<strong> write the function to fetch the data</strong></li><li>Put things on the stove and wait for it to cook i.e. <strong>handle loading states</strong></li><li>Make sure nothing burns, and if it does then you restart the dish i.e. <strong>handling error states</strong></li><li>Cooking multiple dishes at the same time can result in <strong>race conditions</strong></li></ul><p>useQuery on the other hand, is like ordering a meal from a restaurant.</p><ul><li>You place an order i.e. <strong>define the query</strong></li><li>The restaurant (TanStack Query) prepares everything for you i.e. <strong>errors, loading, caching</strong></li><li>You wait for your meal to arrive i.e. <strong>your data response to reach you</strong></li><li>You can reorder the same dish and the restaurant provides it to you quickly i.e. <strong>cached</strong></li><li>If the restaurant can’t provide the dish (it got burnt, delivery lost, restaurant closed, etc), the restaurant notifies you i.e. <strong>handling error states</strong></li></ul><h3>useEffect:</h3><p>Let’s first understand what a useEffect hook is. In React, the useEffect hook is one way to handle an effect or consequence of either an action or a component itself. We can use <strong>useEffect</strong> to update some UI, states, or DOM elements, and even fetch data. useEffect takes in two parameters: a function and a dependency array. So this function will run every time our dependency changes, and if the dependency is not provided, our useEffect will run <strong>every render</strong>.</p><pre>useEffect(() =&gt; {<br>});</pre><p>If we include just an empty array as a dependency then useEffect will run only once during <strong>the first render</strong>.</p><pre>useEffect(() =&gt; {<br>}, []);</pre><p>But if we pass in some actual dependency values such as a state, then the useEffect will run once in the first render and then <strong>every time the state value changes</strong>.</p><pre>useEffect(() =&gt; {<br>}, [state]);</pre><p>React doesn’t have a dedicated hook to fetch data which is a shame as that is one of the key functionalities required by any web app. Instead, one way to do it is to use the useEffect hook to fetch data and update some state variable encapsulating that data.</p><pre>export default function App() {<br>  const [imageUrl, setImageUrl] = useState&lt;string | null&gt;(null);<br><br><br>  async function fetchImage() {<br>    const response = await fetch(&quot;https://picsum.photos/200/300&quot;);<br>    setImageUrl(response.url);<br>    console.log(&quot;Image URL:&quot;, response.url);<br>  }<br><br><br>  useEffect(() =&gt; {<br>    fetchImage(); <br>  }, []); //Fetch image during the first render of the page<br><br><br>  return (<br>    &lt;&gt;<br>      &lt;h1&gt;Testing fetch with useEffect&lt;/h1&gt;<br>      {imageUrl &amp;&amp; &lt;img src={imageUrl} alt=&quot;Random image&quot; /&gt;}<br>      &lt;div className=&quot;card&quot;&gt;<br>        &lt;button onClick={fetchImage}&gt;Fetch new image&lt;/button&gt;<br>      &lt;/div&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><p>In this example, we are fetching some random image from the <a href="https://picsum.photos/">https://picsum.photos</a> url with a width of 200 and a height of 300. We are using the fetchImage function inside of a useEffect, with an empty dependency array so we are fetching the image once during the first render of our page. Then we are displaying the image, as well as a button that uses the fetchImage function again to get a new random image.</p><h4>Error handling with useEffect:</h4><p>This is the beginner way of fetching some data in React. But what if we encounter some error trying to fetch that data? With the current code, we wouldn’t even know what error and when we encountered it. So we need to handle the possibility of getting an error. To do this, we can change our fetchImage function to add some error handling.</p><pre>async function fetchImage() {<br>    try {<br>      const response = await fetch(&quot;https://picsum.photos/200/300&quot;);<br>      setImageUrl(response.url);<br>      console.log(&quot;Image URL:&quot;, response.url);<br>    } catch (error) {<br>      console.error(&quot;Error fetching image:&quot;, error);<br>    }<br>  }</pre><h4>Loading state with useEffect:</h4><p>Ok so now we try fetching the image and if it fails or we have some error, we are displaying the error in our console. But what about while React is fetching the image and waiting for a response? Our page is empty during that loading state and we don’t know whether it’s loading or if something else went wrong so let’s handle the loading state.</p><pre>export default function App() {<br>  const [imageUrl, setImageUrl] = useState&lt;string | null&gt;(null);<br>  const [loading, setLoading] = useState&lt;boolean&gt;(false);<br><br><br>  async function fetchImage() {<br>    setLoading(true);<br>    try {<br>      const response = await fetch(&quot;https://picsum.photos/200/300&quot;);<br>      setImageUrl(response.url);<br>      console.log(&quot;Image URL:&quot;, response.url);<br>    } catch (error) {<br>      console.error(&quot;Error fetching image:&quot;, error);<br>    } finally {<br>      setLoading(false);<br>    }<br>  }<br><br><br>  useEffect(() =&gt; {<br>    fetchImage();<br>  }, []);<br><br><br>  return (<br>    &lt;&gt;<br>      &lt;h1&gt;Testing fetch with useEffect&lt;/h1&gt;<br>      {loading ? (<br>        &lt;p&gt;Loading...&lt;/p&gt;<br>      ) : (<br>        imageUrl &amp;&amp; &lt;img src={imageUrl} alt=&quot;Random image&quot; /&gt;<br>      )}<br>      &lt;div className=&quot;card&quot;&gt;<br>        &lt;button onClick={fetchImage}&gt;Fetch new image&lt;/button&gt;<br>      &lt;/div&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><p>Now we have another state to track whether the image is loading or not, and we display the loading text depending on it. We set loading to true when we enter the fetchImage function as we attempt to get the image from the API and then set loading to false in the <strong>finally block</strong>, regardless of whether we successfully received an image or not.</p><h4>Drawbacks of using useEffect:</h4><p>Phew… that was a lot of things to think about and we are still only using the naive method of fetching data. Even then, we haven’t handled one of our biggest concerns —<strong> caching</strong>. Imagine we have multiple pages in this app and we fetch an image in the first page before we navigate to a new page, if we press the back button to navigate back to the original page our useEffect would fetch the image again from the url and we would get a new random image. This is not what we want. We want to be able to see that initial image we had rendered before we navigated to the second page, that means getting that image from the cache and not refetching it. But caching is not an easy task.</p><p>One of the other key reasons why we don’t want to use the useEffect hook to handle the data fetching is because when we write an asynchronous function we don’t have any idea about how long the function will actually take to complete that request. For example, if we click the<strong> “Fetch New Image”</strong> button to request an image, then click it again before the first request finishes, a <strong>race condition</strong> occurs. We might request image 1 first and image 2 right after, but since responses arrive at unpredictable times, image 1 could load after image 2. This can cause a brief flicker of the wrong image before the latest one appears.</p><p>Using useEffect hook also means that we have to handle everything ourselves: <strong>fetching the data, loading states, error states, caching, managing the state containing the data,</strong> etc. Additionally, we would have to make all these implementations into a custom hook so it is reusable all over our app. But this is a difficult and error prone process. And you know what they say?</p><p><strong><em>Taking the hard path, when there exists an easier already travelled one, is NOT A SMART CHOICE.</em></strong></p><p>I don’t know who says that but I’m sure you get the point.</p><p>So our solution? TanStack Query of course.</p><h3>useQuery:</h3><p>TanStack Query or better known as React Query, is not just a data fetching library, but it helps us manage async states. It provides us with a powerful hook called<strong> useQuery</strong> for handling all those concerns we had — fetching, loading, errors, caching, and much more.</p><p>Do you recall the useEffect error when the incorrect image briefly flickered before the correct one was resolved because of a race condition? We don’t have to worry about this with useQuery. No matter how many times we click the fetch new image button, we always see the final image that our query fetches.</p><p>Using useQuery to redo our component, will look something like this:</p><pre>export default function App() {<br>  async function fetchImage() {<br>    const response = await fetch(&quot;https://picsum.photos/200/300&quot;);<br>    return response.url;<br>  }<br><br>// using useQuery from TanStack instead of useEffect from React<br>  const {<br>    data: imageUrl,<br>    isPending,<br>    error,<br>    refetch,<br>  } = useQuery({<br>    queryKey: [&quot;randomImage&quot;],<br>    queryFn: fetchImage,<br>  });<br><br><br>  return (<br>    &lt;&gt;<br>      &lt;h1&gt;Testing fetch with TanStack Query&lt;/h1&gt;<br>      {isPending ? (<br>        &lt;p&gt;Loading...&lt;/p&gt;<br>      ) : error ? (<br>        &lt;p&gt;Error loading image&lt;/p&gt;<br>      ) : (<br>        imageUrl &amp;&amp; &lt;img src={imageUrl} alt=&quot;Random image&quot; /&gt;<br>      )}<br>      &lt;div className=&quot;card&quot;&gt;<br>        &lt;button<br>          onClick={() =&gt; {<br>            refetch();<br>          }}<br>        &gt;<br>          Fetch new image<br>        &lt;/button&gt;<br>      &lt;/div&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><p>The <strong>useQuery</strong> hook from tanstack query is a treasure box in itself. It takes in a <strong>queryKey</strong> which must be an array with a unique value, and a<strong> queryFn</strong>, the function that fetches the data. With useQuery, our fetchImage function becomes much simpler — it only fetches and returns the image URL, without us having to manage loading or error states manually. useQuery is a treasure box that gives us the option to choose any treasure we want from it: <strong>the fetched data, loading and error states, pending status, and even a function to refetch data</strong>. In our example, we get the image URL (imageUrl), the isPending state, any errors, and a refetch function — all handled seamlessly by useQuery.</p><p>So now, if we navigate away and return, the image is retrieved from the cache instead of refetching. Also, no need to manually track loading or errors — they’re built-in!</p><h4>Why use isPending and not isLoading?</h4><p>isLoading is true only when the first fetch for a query is taking place, while isPending tells us if there’s any cached data available. This is why, when we click the “Fetch New Image” button, we no longer see a loading message — the current image remains visible until the new request resolves.</p><p>While we are at it, let’s also look at a very common use case for data fetching which requires us to pass in parameters to the query. For example we can get a specific image from picsum.photos by using an id, and we can change this id later in our app maybe by a button click.</p><pre>export default function App() {<br>  const [id, setId] = useState(1);<br>  async function fetchImage(id: number) {<br>    const response = await fetch(`https://picsum.photos/id/${id}/200/300`);<br>    return response.url;<br>  }<br><br><br>  const {<br>    data: imageUrl,<br>    isPending,<br>    error,<br>  } = useQuery({<br>    queryKey: [&quot;randomImage&quot;, id],<br>    queryFn: () =&gt; fetchImage(id),<br>  });<br><br><br>  return (<br>    &lt;&gt;<br>      &lt;h1&gt;Testing fetch with TanStack Query&lt;/h1&gt;<br>      {isPending ? (<br>        &lt;p&gt;Loading...&lt;/p&gt;<br>      ) : error ? (<br>        &lt;p&gt;Error loading image&lt;/p&gt;<br>      ) : (<br>        imageUrl &amp;&amp; &lt;img src={imageUrl} alt=&quot;Random image&quot; /&gt;<br>      )}<br>      &lt;div className=&quot;card&quot;&gt;<br>        &lt;button<br>          onClick={() =&gt; {<br>            setId((prev) =&gt; prev + 1);<br>          }}<br>        &gt;<br>          Increment image id<br>        &lt;/button&gt;<br>      &lt;/div&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><p>Now we have a state variable called id with a default value of 1, so we get the image with id=1 as our starting image always. When we click on the increment button we are changing the state variable by adding 1 to it. With useEffect we would have needed to handle the state update for this id manually but useQuery makes it so much easier. We just need to pass in the id to the<strong> queryKey</strong> so that TanStack can cache the query accurately. So whenever we have variables or parameters needed for a query that will change the result of the query, we need to have that variable as part of our <strong>queryKey</strong>.</p><p>As you can now see, with just a few lines of code we’ve effortlessly handled:</p><ul><li>Data fetching</li><li>Loading and Error states</li><li>Caching</li><li>Race conditions</li></ul><p>That’s the magic of <strong>useQuery</strong>. And this is just the beginning — our example barely scratches the surface of what it can do. Hopefully, this has convinced you to give it a try!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87f9ef9012e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[In Layman’s Terms III: Classes and Inheritance]]></title>
            <link>https://medium.com/@maishaChow/in-laymans-terms-iii-classes-and-inheritance-b6f046e6799f?source=rss-34a3913dfc05------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6f046e6799f</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[inheritance]]></category>
            <category><![CDATA[classes-and-objects]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Maisha Supritee Chowdhury]]></dc:creator>
            <pubDate>Mon, 23 Dec 2024 06:40:10 GMT</pubDate>
            <atom:updated>2024-12-23T06:40:10.436Z</atom:updated>
            <content:encoded><![CDATA[<h3>Class</h3><p>Previously I’ve explained functions as recipes, let’s think of classes now as a <strong>blueprint.</strong></p><p><em>What is a blueprint?</em></p><p>It’s like a design which if followed, can help us create something the exact same way every time. Let’s say we have a class called Bird. So, a bird can have some properties such as the type of bird, their name, and even age. We can assign these properties/attributes to our Bird class and every time we want a bird, the Bird class will create a bird with the kind, name and age of the bird we pass into it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z7xVZMW8XP6ANRGGBudzQw.jpeg" /></figure><p>So a class gives you the skeleton of the type of objects it can create, while an object is a specific case of that class. In our example we have the Bird class and then every Bird we make using it: Parrot, Sparrow, Raven, are objects of the Bird class.</p><pre>class Bird:<br>  def __init__(self, kind, name, age):<br>   self.kind = kind<br>   self.name = name<br>   self.age = age</pre><p>In python every class has a<strong> __init__</strong> function which is a constructor function that runs whenever an object of the class is created for the first time. This function is responsible for assigning values to the attributes of that object. With the above init function, our Bird class always expects a kind, name and age value to be passed into it whenever we create an object from Bird.</p><p><strong>To create objects:</strong></p><pre>parrot = Bird(“Parrot”, “Jack”, 2)<br>sparrow = Bird(&quot;Sparrow&quot;, &quot;Joy&quot;, 1.4)<br>raven = Bird(&quot;Raven&quot;, &quot;Dan&quot;, 5)</pre><p>Now we can individually access the parrot’s age, name and kind if we wish to.</p><pre>parrot.age = 3<br>print(&quot;My name is &quot; + parrot.name + &quot; and I am a &quot; + parrot.kind + &quot;. I am &quot;, parrot.age, &quot; years old!&quot;)</pre><p><strong>Result:</strong><br><em>My name is Jack and I am a Parrot. I am 3 years old!</em></p><p>Right now, our class only has some attributes, but classes can also have their own functions!</p><pre>class Bird:<br>  def __init__(self, kind, name, age):<br>    self.kind = kind<br>    self.name = name<br>    self.age = age<br><br>  def intro(self):<br>    print(&quot;Hello my name is &quot; + self.name + &quot; and I am a &quot; + self.kind + &quot;. I am &quot;, self.age, &quot; years old!&quot;)<br><br>parrot = Bird(&quot;Parrot&quot;, &quot;Jack&quot;, 2)<br>sparrow = Bird(&quot;Sparrow&quot;, &quot;Joy&quot;, 1.4)<br>raven = Bird(&quot;Raven&quot;, &quot;Dan&quot;, 5)<br>parrot.intro()<br>sparrow.intro()<br>raven.intro()</pre><p><strong>Results:</strong><br><em>Hello my name is Jack and I am a Parrot. I am 2 years old!</em></p><p><em>Hello my name is Joy and I am a Sparrow. I am 1.4 years old!</em></p><p><em>Hello my name is Dan and I am a Raven. I am 5 years old!</em></p><p>So, when we make an object from a class, it receives all the variables and functions that belong to the class. Parrot will have a name and age and intro, as well as the Raven and the Sparrow.</p><h3>Inheritance:</h3><p>Suppose we have a class called GameCharacter, that means everything within this class is a blueprint on how to make a character for our game. Our game can have multiple types of characters such as a player, enemy or even NPCs (non playable characters). To make all these different characters we can have separate subclasses such as a Player class which would have instructions on how to make a player, an Enemy class with instructions on how to make an enemy and so on.</p><p>So, you might think, why not just make the game character as just objects of the GameCharacter class? For example, our player can perform complex actions like attacking and defending, while NPCs, which might lack the ability to attack, should not have access to the attack function. Additionally, enemies may have unique attack methods distinct from the player’s, so they should not share the same attack function. To ensure these separations in behavior we can use subclasses/child classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qefHkw6TD9KV6Rv21GRBng.jpeg" /></figure><p>We have the GameCharacter class which is our parent class and Player, Enemy and NPC which are the child classes.</p><pre>class GameCharacter:<br>  def __init__(self, name, health, position):<br>    self.name = name<br>    self.health = health<br>    self.position = position<br>    self.is_alive = True<br><br>  def move_to(self, destination):<br>    self.position = destination<br><br>  def die(self):<br>    self.is_alive = False<br>    print(f&quot;{self.name} has died.&quot;)</pre><p>To create our child classes and have them inherit functionality from their parent class GameCharacter, we need to send the parent class in as a parameter to our child class.</p><pre>class Player(GameCharacter):<br>  pass</pre><p>Right now, our Player class doesn’t have any attributes or functions of its own, that’s why we are using <strong>pass</strong>. But the Player class does inherit all the attributes such as <strong>name, heath, position, is_alive</strong> and all the functions such as <strong>move_to</strong> and <strong>die</strong> from the GameCharacter class. However this is a useless class as it’s not doing anything different from its parent. So let’s spice it up!</p><pre>class Player(GameCharacter):<br>  def __init__(self, name, health, position, inventory):</pre><p>If we add the __init__ function to our Player class it will no longer inherit the __init__ function from GameCharacter class. But the __init__ function for Player class will be doing everything that GameCharacter’s init does except for an extra attribute: inventory. So, the better option would be to inherit this function from GameCharacter and then write extra code to handle the inventory.</p><p>There are 2 ways to deal with this:</p><pre>class Player(GameCharacter):<br>  def __init__(self, name, health, position, inventory):<br>    GameCharacter().__init__(name, health, position)<br>    self.inventory = inventory</pre><p>This will inherit just the __init__ function from GameCharacter.</p><pre>class Player(GameCharacter):<br>  def __init__(self, name, health, position, inventory):<br>    super().__init__(name, health, position)<br>    self.inventory = inventory</pre><p>The <strong>super()</strong> function makes the child class inherit all of the attributes and functions of its parent class. This is the better choice for us as we also want our Player to have the move_to and die functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uYkevcXh7oS-OTokldmoxw.jpeg" /></figure><p>So only the Player has the function attack and the attribute inventory, only the Enemy has the function chase and the attribute experience, and only NPC has the function speak and the attribute dialogue. But all three of the classes have the attributes: <strong>name, health, position, is_alive</strong> and the functions: <strong>move_to, and die</strong>.</p><pre>class GameCharacter:<br>    def __init__(self, name, health, position):<br>        self.name = name<br>        self.health = health<br>        self.position = position<br>        self.is_alive = True<br><br>    def move_to(self, destination):<br>        self.position = destination<br><br>    def die(self):<br>        self.is_alive = False<br>        print(f&quot;{self.name} has died.&quot;)<br><br>class Player(GameCharacter):<br>    def __init__(self, name, health, position, inventory):<br>        super().__init__(name, health, position)<br>        self.inventory = inventory<br><br>    def attack(self, target):<br>        print(f&quot;{self.name} attacks {target.name}!&quot;)<br><br>class Enemy(GameCharacter):<br>    def __init__(self, name, health, position, experience):<br>        super().__init__(name, health, position)<br>        self.experience = experience<br><br>    def chase(self, target):<br>        print(f&quot;{self.name} is chasing {target.name}!&quot;)<br><br>class NPC(GameCharacter):<br>    def __init__(self, name, health, position, dialogue):<br>        super().__init__(name, health, position)<br>        self.dialogue = dialogue<br><br>    def speak(self):<br>        print(f&quot;{self.name} says: &#39;{self.dialogue}&#39;&quot;)</pre><p>Now, that we have all the classes let’s get to the fun part — creating a player, enemy and NPC!</p><pre># Create a Player object<br>player1 = Player(<br>    name=&quot;Harry Potter&quot;,<br>    health=100,<br>    position=(0, 0),  # Starting position (x, y)<br>    inventory=[&quot;Wand&quot;, &quot;Sword&quot;, &quot;Potion&quot;]  # Inventory items<br>)<br><br>print(f&quot;Player Created: {player1.name}, Health: {player1.health}, Inventory: {player1.inventory}&quot;)<br><br># Create an Enemy object<br>enemy1 = Enemy(<br>    name=&quot;Voldemort&quot;,<br>    health=71,<br>    position=(10, 5),  # Starting position (x, y)<br>    experience=10  # Experience from 1 to 10<br>)<br><br>print(f&quot;Enemy Created: {enemy1.name}, Health: {enemy1.health}, Aggression Level: {enemy1.experience}&quot;)<br><br># Create an NPC object<br>npc1 = NPC(<br>    name=&quot;Neville Longbottom&quot;,<br>    health=70,  <br>    position=(5, 5),  # Starting position (x, y)<br>    dialogue=&quot;Hello, Harry! Welcome to Hogwarts.&quot;  <br>)<br><br>print(f&quot;NPC Created: {npc1.name}, Dialogue: &#39;{npc1.dialogue}&#39;&quot;)</pre><p><strong>Results:</strong><br><em>Player Created: Harry Potter, Health: 100, Inventory: [‘Wand’, ‘Sword’, ‘Potion’]</em></p><p><em>Enemy Created: Voldemort, Health: 71, Aggression Level: 10</em></p><p><em>NPC Created: Neville Longbottom, Dialogue: ‘Hello, Harry! Welcome to Hogwarts.’</em></p><p><strong>For all my witches and wizards:</strong> hope you enjoy the Harry potter references!</p><p><strong>For all my muggleborns</strong>: don’t mind me indulging my inner Potterhead.</p><p>We can use the functions from GameCharacter and the child classes now to progress the game.</p><pre>player1.move_to(200)<br>enemy1.chase(player1)<br>player1.attack(enemy1)<br>enemy1.die()</pre><p><strong>Results:</strong><br><em>Voldemort is chasing Harry Potter!</em></p><p><em>Harry Potter attacks Voldemort!</em></p><p><em>Voldemort has died.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wPPQhv9-KmDoamSiu4hfYw.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6f046e6799f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[In Layman’s Terms II: Functions and Scope]]></title>
            <link>https://medium.com/@maishaChow/in-laymans-terms-ii-functions-and-scope-931b96b88656?source=rss-34a3913dfc05------2</link>
            <guid isPermaLink="false">https://medium.com/p/931b96b88656</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[function]]></category>
            <category><![CDATA[scopes]]></category>
            <dc:creator><![CDATA[Maisha Supritee Chowdhury]]></dc:creator>
            <pubDate>Thu, 04 Jul 2024 23:22:35 GMT</pubDate>
            <atom:updated>2024-10-19T00:17:32.617Z</atom:updated>
            <content:encoded><![CDATA[<h3>Functions</h3><p>A function is a block of code used to perform an action in a program. So, when we have multiple lines of code that all together instruct our program to do a specific task, we put them in a function.</p><p>This task can be anything simple like adding two numbers to more complicated tasks like reading the contents of a file. A function will never run if its not “<strong>called</strong>.” When we use a function, this is known as “<strong>calling</strong>” a function. So how do we call a function? Simply by writing <strong><em>functionName()</em></strong>. A variable in code can be used just by writing its name for example: <strong><em>variableName = 1</em></strong>, but a function always has brackets/parenthesis beside it. There may be something inside these brackets or not.</p><p>Think of a function like a recipe. What does a recipe do? Gives us step by step instructions on how to make a dish. A function does the same thing, gives step by step instructions in code so our program can make something. A recipe always needs ingredients. Similarly, a function also uses ingredients. We can either give the ingredients to the function when we use it or make the ingredients inside of the function itself. These ingredients are known as <strong>arguments/parameters</strong> of the function.</p><p>For example: a function to add two numbers in Python</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TwT8kTjEZvHrdWFM8lT7FA.jpeg" /></figure><p>As you can see above, not only can a function take in ingredients <strong>(arguments/parameters)</strong>, but all functions must also specify what type of information it is going to give out/<strong>return</strong> when it is used. This function takes in two ingredients: x and y, both of type integers and the actual code inside the function only adds the two and stores it in another variable called result. Finally, the function returns this result.</p><p>So, when we call this addition function we made, we just call it like:</p><pre>x = 10<br>y = 20<br>addition(x,y)</pre><p>The same function addition in C++:</p><pre>int addition(int x, int y)<br>{<br>    int result = x+y;<br>    return result;<br>}</pre><p>The return type of the function is int, and the data type for each of the arguments x and y are also int.</p><p>But passing arguments to a function is optional. We can also make functions that do not need any arguments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_igiZEqzDL5-J0EouCEWYQ.jpeg" /></figure><p>When we call this version of the addition function now, we just write:</p><pre>addition()</pre><p>But since the addition function is not printing anything itself, and it returns a value, it makes more sense to store what we get back from this function into another variable.</p><pre>result = addition()<br>print(result)</pre><p>Now, we can actually see the result 30 be printed out on our screen.</p><p>Different languages will have separate ways to write a function. While the examples I am using are with Python and C++, you still need both: arguments and return type, when you write a function in any language of your choice, just written differently.</p><p>But what if we want to write a function that does not return anything? It is simple. At least for python. You just do not return anything.</p><pre>def addition():<br>  x = 10 <br>  y = 20<br>  result = x+y<br>  print(result)</pre><p>For C++, if we want to write a function that does not return anything, the return type of the function is <strong>void</strong>.</p><pre>void addition()<br>{<br>    int x = 10;<br>    int y = 20;<br>    int result = x+y;<br>    cout&lt;&lt;result;<br>}</pre><p>The function above does not return anything, instead it only prints the result of adding those two numbers.</p><p>We can also make a function inside of another function. For example in Python:</p><pre>def additionSubtraction():<br>  x = 10<br>  y = 20<br>  result = x+y<br>  def subtraction() -&gt; int:<br>    a = 5<br>    b = 2<br>    return (a-b)<br>  innerResult = subtraction()<br>  print(result, innerResult)<br>additionSubtraction()</pre><p>The outer function adds two random numbers, while the inner subtracts two random numbers. The inner function is being called inside the outer function and its result is stored in another variable called innerResult. The function<strong> additionSubtraction</strong> prints both its own result and the inner function’s result. Finally in the main body of our code outside of any functions, we are calling the <strong>additionSubtraction()</strong> function to actually see the output. This function is very weird and useless, but you get the point.</p><h3>Scope</h3><p>Scope means the range of something. What does a scope mean in terms of programming? A scope in programming refers to the range/area within which we can use a variable. There are two types of scopes:</p><h4>Local Scope</h4><p>A variable we make inside of a function belongs to that function and can only be used inside of that function. So that variable is “local” to that function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dXVRQfHvgAH1ji6vDghCKQ.jpeg" /></figure><p>If we try to use these variables: x, y, and result in any other function or just anywhere outside of the addition function it will give us an error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uIZVvLw9mOAnhcZRXFSw7w.jpeg" /></figure><p>Local variables within one function can be used inside its inner function as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T6F7Kb-KhRVBfk9sCo8_4g.jpeg" /></figure><h4>Global Scope</h4><p>When we make a variable in the main python body, not inside any specific function, it is known as a global variable. This means that variable can be used inside of any function, any scope, i.e. anywhere we want in our code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sOEdTrXLX242orcK-nozvg.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=931b96b88656" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[In Layman’s Terms: Variables and Data Types]]></title>
            <link>https://medium.com/@maishaChow/in-laymans-terms-variables-and-data-types-d6cb1678d857?source=rss-34a3913dfc05------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6cb1678d857</guid>
            <category><![CDATA[variables]]></category>
            <category><![CDATA[laymans-terms]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-type]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Maisha Supritee Chowdhury]]></dc:creator>
            <pubDate>Sat, 22 Jun 2024 00:49:51 GMT</pubDate>
            <atom:updated>2024-10-19T00:01:38.104Z</atom:updated>
            <content:encoded><![CDATA[<p>I am the type of person that learns best by writing and explaining things to others. Since I am teaching coding to kids with no background in it, I have decided to start a series where I explain what I am learning and teaching in Layman’s terms. This way, I can help both myself and maybe others understand these concepts better. The programming language for the coding snippets I use in these series of articles will switch between Python, C++, and Java often. The language used is not the focus of the articles, it’s the underlying concepts that I want to explain, and so I will be flipping between languages that suit the concept more.</p><p>Well, I cannot start explaining anything in Layman’s terms without explaining what the layman’s term stands for. Layman’s term means to explain something in its simplest form, or in plain English (Merriam-Webster, n.d). For example:</p><p><strong><em>I aspire to augment my comprehension of coding paradigms by elucidating them to others.</em></strong></p><p>I must be honest; I did not even know the word elucidate before today. This above sentence full of unnecessary jargon can be simplified in Layman’s terms to:</p><p><strong><em>I hope to improve my understanding of coding concepts by explaining them to others.</em></strong></p><p>Now that sounds much better! So, let us get started.</p><h3>Variables and Data Types</h3><p>The first thing I ever learned when I started coding was a variable. A variable is like a box we can use to store items in. When we have leftover food, where do we store them? In a box. Snacks? Store them in a box. Medicine? Books? Electronics? Store them all in a box. When we want to write a program we need to store a lot of different data, for which we need variables. This brings us to data types.</p><p>Do you store a book in the same box as a curry? I hope not. Generally, we store food in one box, books in another, medicines in another and so on. Similarly, for variables also we need to store different types of data in different types of variables. Let us cover the most basic data types:</p><p><strong>int (Integer) -&gt; All numbers that are not fractions/decimals. For example: -89, 0, 400.</strong></p><p>Int in C++:</p><pre>int num = 7;</pre><p><strong>float (Floating point) -&gt; All numbers that are fractions/decimals. For example: -3.25, 0.50.</strong></p><p>Float in C++:</p><pre>float y = -2.5;</pre><p><strong>double -&gt; Same as float, it stores all numbers that are fractions/decimals, but it is twice the size of float.</strong> You can store a decimal number with max seven digits accurately in a box of type float such as 5.123456, while you can store a decimal number with max fifteen digits accurately in a box of type double such as 5.12345678912345.</p><p>Double in C++:</p><pre>double x = 8.965;</pre><p><strong>char (Character) -&gt; A single letter, blank space, punctuation mark or symbol surrounded by a single quotation mark. For example: ‘d’, ‘!’, ‘$’, ‘&amp;’.</strong></p><p>Char in C++:</p><pre>char c = ‘H’;</pre><p><strong>bool (Boolean) -&gt; True or False. For example: true/1, false/0.</strong></p><p>Bool in C++:</p><pre>bool isReal = false;</pre><p><strong>string (String) -&gt; A collection of characters, symbols, punctuation marks, or numbers, surrounded by double quotation marks. For example: “string”, “$$dollar!”, “123456”.</strong></p><p>String in C++:</p><pre>string name = “Joe”;</pre><p>Now that we know a basic variable, another way of storing a value in a program is using constants.</p><h3>Constants</h3><p>A constant is a value that cannot be changed once it has been declared. Think of a piggy bank with only a slot to insert coins but no way to take them out other than by breaking the bank itself. For variables we can change the value stored inside it whenever we want, but for a constant, it can never be changed after initialization. Constants are almost always named using upper case letters as well.</p><p>Constants in C++:</p><pre>const int NUM = 100;</pre><p>You might think, why do we even need constants when we already have variables? Because we need a way to store items in our program that will always remain the same value, and we do not want ourselves, other programmers or even the program itself to somehow change said value. If we think of it in terms of a piggy bank, being able to take out money whenever we want might prevent us from saving $100. However, if we can only take out money by breaking the bank, it may encourage us to avoid touching our savings, leading to more savings over time.</p><p><strong>References</strong></p><p>Merriam-Webster. (n.d.). Layman’s terms. In Merriam-Webster.com dictionary. Retrieved June 21, 2024, from <a href="https://www.merriam-webster.com/dictionary/layman%27s%20terms">https://www.merriam-webster.com/dictionary/layman%27s%20terms</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6cb1678d857" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>