<?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:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" xmlns:googleplay="http://www.google.com/schemas/play-podcasts/1.0"><channel><title><![CDATA[Tech Newsletter]]></title><description><![CDATA[My personal Substack]]></description><link>https://sanjayofficial.substack.com</link><image><url>https://substackcdn.com/image/fetch/$s_!1_BZ!,w_256,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fed45dfa0-af8f-4f62-88aa-ea651f831f3a_640x640.jpeg</url><title>Tech Newsletter</title><link>https://sanjayofficial.substack.com</link></image><generator>Substack</generator><lastBuildDate>Sun, 05 Apr 2026 11:13:57 GMT</lastBuildDate><atom:link href="https://sanjayofficial.substack.com/feed" rel="self" type="application/rss+xml"/><copyright><![CDATA[Sanjay Mehta]]></copyright><language><![CDATA[en]]></language><webMaster><![CDATA[sanjayofficial@substack.com]]></webMaster><itunes:owner><itunes:email><![CDATA[sanjayofficial@substack.com]]></itunes:email><itunes:name><![CDATA[Sanjay Mehta]]></itunes:name></itunes:owner><itunes:author><![CDATA[Sanjay Mehta]]></itunes:author><googleplay:owner><![CDATA[sanjayofficial@substack.com]]></googleplay:owner><googleplay:email><![CDATA[sanjayofficial@substack.com]]></googleplay:email><googleplay:author><![CDATA[Sanjay Mehta]]></googleplay:author><itunes:block><![CDATA[Yes]]></itunes:block><item><title><![CDATA[Generative AI in a Nutshell – Mastering the Future of Intelligence]]></title><description><![CDATA[A Beginner-Friendly Journey Through Generative AI, Explained with Clarity and Context]]></description><link>https://sanjayofficial.substack.com/p/generative-ai-in-a-nutshell-mastering</link><guid isPermaLink="false">https://sanjayofficial.substack.com/p/generative-ai-in-a-nutshell-mastering</guid><dc:creator><![CDATA[Sanjay Mehta]]></dc:creator><pubDate>Sun, 04 May 2025 11:41:45 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!3Ukj!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F1cd9399e-6e25-41f3-87e1-3410315626cf_1174x660.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!3Ukj!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F1cd9399e-6e25-41f3-87e1-3410315626cf_1174x660.webp" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!3Ukj!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F1cd9399e-6e25-41f3-87e1-3410315626cf_1174x660.webp 424w, https://substackcdn.com/image/fetch/$s_!3Ukj!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F1cd9399e-6e25-41f3-87e1-3410315626cf_1174x660.webp 848w, https://substackcdn.com/image/fetch/$s_!3Ukj!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F1cd9399e-6e25-41f3-87e1-3410315626cf_1174x660.webp 1272w, https://substackcdn.com/image/fetch/$s_!3Ukj!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F1cd9399e-6e25-41f3-87e1-3410315626cf_1174x660.webp 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!3Ukj!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F1cd9399e-6e25-41f3-87e1-3410315626cf_1174x660.webp" width="1174" height="660" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/1cd9399e-6e25-41f3-87e1-3410315626cf_1174x660.webp&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:660,&quot;width&quot;:1174,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:69044,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/webp&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:&quot;https://sanjayofficial.substack.com/i/162810114?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F1cd9399e-6e25-41f3-87e1-3410315626cf_1174x660.webp&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!3Ukj!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F1cd9399e-6e25-41f3-87e1-3410315626cf_1174x660.webp 424w, https://substackcdn.com/image/fetch/$s_!3Ukj!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F1cd9399e-6e25-41f3-87e1-3410315626cf_1174x660.webp 848w, https://substackcdn.com/image/fetch/$s_!3Ukj!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F1cd9399e-6e25-41f3-87e1-3410315626cf_1174x660.webp 1272w, https://substackcdn.com/image/fetch/$s_!3Ukj!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F1cd9399e-6e25-41f3-87e1-3410315626cf_1174x660.webp 1456w" sizes="100vw" fetchpriority="high"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><h4>The world is buzzing with AI, but are we truly understanding it? </h4><h4>In this article, we break down generative AI and how it is different from traditional AI, models, and the mindset needed to thrive in this era of rapid transformation.</h4><h4>Let&#8217;s break it down:</h4><h2>Traditional AI vs Generative AI</h2><h5><strong>1. Purpose</strong></h5><ul><li><p><strong>Traditional AI</strong>: Designed to <strong>analyze</strong> data, recognize patterns, and make <strong>predictions</strong> or <strong>classifications</strong>.</p></li><li><p><strong>Generative AI</strong>: Designed to <strong>create</strong> new content like text, images, audio, or even code.</p></li></ul><h5><strong>2. Input &amp; Output</strong></h5><ul><li><p><strong>Traditional AI</strong>: Takes structured data &#8594; gives <strong>answers</strong>, <strong>labels</strong>, or <strong>scores</strong>.</p></li><li><p><strong>Generative AI</strong>: Takes prompts (text, image, etc.) &#8594; generates <strong>original</strong> outputs like a paragraph, image, or video.</p></li></ul><h5><strong>3. Use Cases</strong></h5><ul><li><p><strong>Traditional AI</strong>: Spam detection, fraud analysis, recommendation systems, forecasting.</p></li><li><p><strong>Generative AI</strong>: Writing emails, designing visuals, coding assistants, chatbots, storytelling.</p></li></ul><h5><strong>4. Data Requirements</strong></h5><ul><li><p><strong>Traditional AI</strong>: Needs <strong>labeled datasets</strong> (e.g., thousands of images labeled "cat" or "not cat").</p></li><li><p><strong>Generative AI</strong>: Trained on <strong>massive, unstructured data</strong> (books, web pages, images, audio) to learn how to generate.</p></li></ul><h5><strong>5. Examples</strong></h5><ul><li><p><strong>Traditional AI</strong>: Logistic Regression, Decision Trees, SVMs, Random Forests.</p></li><li><p><strong>Generative AI</strong>: GPT, Claude, DALL&#183;E, Midjourney, Copilot, Gemini.</p></li></ul><h5><strong>6. Flexibility</strong></h5><ul><li><p><strong>Traditional AI</strong>: <strong>Narrow</strong>, task-specific models.</p></li><li><p><strong>Generative AI</strong>: <strong>Broad</strong>, multi-purpose models with emergent capabilities.</p></li></ul><h5><strong>7. Interaction</strong></h5><ul><li><p><strong>Traditional AI</strong>: One-way interaction &#8211; input &#8594; output.</p></li><li><p><strong>Generative AI</strong>: Conversational and dynamic &#8211; context evolves over time.</p><p></p></li></ul><p><strong>Traditional AI</strong> is like a <strong>calculator</strong>&#8212;fast, precise, but rigid.<br><strong>Generative AI</strong> is like a <strong>creative partner</strong>&#8212;flexible, surprising, and increasingly capable.</p><div><hr></div><h2>Popular LLMs You Should Know</h2><p>Large Language Models (LLMs) are trained on vast text datasets and learn to predict and generate coherent sequences. Here are the frontrunners:</p><ul><li><p><strong>GPT-4 / GPT-3.5 (OpenAI)</strong> &#8211; Versatile, good reasoning, great API ecosystem.</p></li><li><p><strong>Claude (Anthropic)</strong> &#8211; Safer, longer memory, context-aware.</p></li><li><p><strong>Gemini (Google)</strong> &#8211; Strong multimodal capabilities.</p></li><li><p><strong>LLaMA (Meta)</strong> &#8211; Open-source research foundation.</p></li><li><p><strong>Command R+ (Cohere)</strong> &#8211; Focused on retrieval-augmented generation (RAG).</p></li><li><p><strong>Mistral / Mixtral</strong> &#8211; Lightweight, open models with high performance.</p></li></ul><p>Most of these are evolving rapidly and being fine-tuned for speed, safety, and specific domains like legal, medical, or customer service.</p><div><hr></div><h2>What Are Multimodal Models?</h2><p>Multimodal models process <strong>multiple types of input/output</strong>:</p><ul><li><p><strong>Text + Image</strong> (e.g., GPT-4 Vision, Gemini)</p></li><li><p><strong>Text + Audio</strong> (e.g., Whisper, AudioCraft)</p></li><li><p><strong>Text + Video</strong> (e.g., Sora by OpenAI)</p></li><li><p><strong>Text + Code + Graphs</strong> (e.g., Claude, Copilot)</p></li></ul><h5>They can:</h5><ul><li><p><strong>Analyze images with text prompts</strong></p></li><li><p><strong>Describe visuals</strong></p></li><li><p><strong>Transcribe speech to text</strong></p></li><li><p><strong>Create videos from descriptions</strong></p></li></ul><p><strong>Use case:</strong> Ask GPT-4 Vision to explain a chart, identify design flaws, or write code from a screenshot.</p><div><hr></div><h2>Prompt Engineering: The New Literacy</h2><p>Getting better results isn&#8217;t about magic&#8212;it&#8217;s about <strong>precision and context</strong>.</p><h3>Key Techniques:</h3><ol><li><p><strong>Be explicit</strong><br><em>&#8220;Write a 100-word summary of this article in a casual tone.&#8221;</em></p></li><li><p><strong>Give examples</strong><br><em>&#8220;Here&#8217;s a good intro: &#8216;In today&#8217;s fast-paced world...&#8217; &#8212; write something similar.&#8221;</em></p></li><li><p><strong>Set constraints</strong><br><em>&#8220;Avoid buzzwords. Use plain English. No more than 3 paragraphs.&#8221;</em></p></li><li><p><strong>Iterate &amp; refine</strong><br><em>&#8220;Now make it more persuasive.&#8221; &#8594; &#8220;Add a quote.&#8221; &#8594; &#8220;Simplify language.&#8221;</em></p></li><li><p><strong>Use roles</strong><br><em>&#8220;Act as a product manager. Give a roadmap for an MVP.&#8221;</em></p></li></ol><div><hr></div><h3>Common Prompt Patterns in Prompt Engineering</h3><h4>1. <strong>Persona Prompt</strong></h4><p>Let the AI act like a specific character or expert.</p><p><strong>Purpose:</strong> Set tone, style, or context.</p><p><strong>Prompt Example:</strong></p><blockquote><h5>"You are a senior software engineer with 10 years of experience. Explain caching to a junior developer."</h5></blockquote><p><strong>Why it works:</strong> Gives the AI a <em>role</em>, shaping its language and depth.</p><h4>2. <strong>Few-shot Prompt</strong></h4><p>Show a few examples before asking a new question.</p><p><strong>Purpose:</strong> Teach the AI by example, especially when tasks aren&#8217;t well-defined.</p><p><strong>Prompt Example:</strong></p><pre><code>Q: What is the capital of France?
A: Paris
Q: What is the capital of Germany?
A: Berlin
Q: What is the capital of Italy?
A:</code></pre><p><strong>Why it works:</strong> Helps guide the model&#8217;s pattern recognition.</p><h4>3. <strong>Zero-shot Prompt</strong></h4><p>Ask directly, without examples.</p><p><strong>Purpose:</strong> Simple tasks where examples aren&#8217;t needed.</p><p><strong>Prompt Example:</strong></p><blockquote><h5>"Translate &#8216;Good morning&#8217; to Spanish."</h5></blockquote><p><strong>Why it works:</strong> Large models like GPT are capable of many zero-shot tasks thanks to broad training data.</p><h4>4. <strong>Chain-of-Thought (CoT) Prompt</strong></h4><p>Ask the model to &#8220;think step by step.&#8221;</p><p><strong>Purpose:</strong> Improve reasoning, math, logic tasks.</p><p><strong>Prompt Example:</strong></p><blockquote><h5>"If I have 3 apples and buy 2 more, how many do I have? Let's think step by step."</h5></blockquote><p><strong>Why it works:</strong> Encourages the model to break down reasoning before jumping to the answer.</p><h4>5. <strong>Instruction Prompt</strong></h4><p>Clearly tell the model what to do.</p><p><strong>Purpose:</strong> Guide the model with commands.</p><p><strong>Prompt Example:</strong></p><blockquote><h5>"Summarize the following text in 3 bullet points."</h5></blockquote><p><strong>Why it works:</strong> Reduces ambiguity&#8212;crystal-clear instructions improve output quality.</p><h4>6. <strong>Reflexive Prompt</strong></h4><p>Ask the model to critique or improve its own answer.</p><p><strong>Purpose:</strong> Refine or validate output.</p><p><strong>Prompt Example:</strong></p><blockquote><h5>"Rewrite your answer to be more concise and professional."</h5></blockquote><p><strong>Why it works:</strong> Encourages iterative improvement.</p><h4>7. <strong>Multi-turn Prompt (Contextual Prompting)</strong></h4><p>Build context across a conversation.</p><p><strong>Purpose:</strong> Complex tasks like coaching, tutoring, or ongoing chats.</p><p><strong>Prompt Example:</strong></p><ol><li><p>"Can you explain recursion?"</p></li><li><p>"Now, can you show me how it works in Python?"</p></li></ol><p><strong>Why it works:</strong> Maintains context over time for personalized interaction.</p><h3>Tips for Effective Prompting</h3><ul><li><p>Use <strong>clear instructions</strong></p></li><li><p>Set <strong>context</strong> with roles/personas</p></li><li><p>Provide <strong>examples</strong> where possible</p></li><li><p>Ask for <strong>step-by-step</strong> reasoning for complex tasks</p></li><li><p>Use <strong>feedback loops</strong> for refinement</p></li></ul><div><hr></div><h2>How to Use LLMs in Real Life</h2><h5><strong>For Developers:</strong></h5><ul><li><p>Code suggestions, debugging, API docs summarization.</p></li><li><p>ChatOps bots, CLI tools, GitHub Copilot.</p></li></ul><h5><strong>For Designers:</strong></h5><ul><li><p>Image generation, UX copywriting, Figma plugins with AI.</p></li></ul><h5><strong>For Business Professionals:</strong></h5><ul><li><p>Email drafting, meeting summarization, pitch polishing.</p></li></ul><h5><strong>For Data Folks:</strong></h5><ul><li><p>SQL generation, data cleaning scripts, insight explanation.</p></li></ul><h5><strong>For Content Creators:</strong></h5><ul><li><p>LinkedIn post ideas, blog outlines, video scripts, newsletter automation.</p></li></ul><div><hr></div><h2>Building vs Using Generative AI</h2><p>You don&#8217;t have to build your own model. Instead:</p><ul><li><p>Use <strong>OpenAI API</strong>, <strong>Anthropic Claude</strong>, <strong>HuggingFace Spaces</strong>, <strong>LangChain</strong>, or <strong>Flowise</strong> to integrate LLMs into apps.</p></li><li><p>Build custom apps for internal tools, customer support, automation, or ideation.</p></li></ul><div><hr></div><h2>The Only Limit: Your Imagination</h2><p>Whether you&#8217;re a developer, marketer, analyst, or student&#8212;generative AI is a toolset that levels the playing field. The challenge isn&#8217;t learning the tool. It&#8217;s learning how to <strong>ask the right questions</strong>.</p><div><hr></div><h2>Bottom Line:</h2><ul><li><p><strong>Traditional AI predicts. Generative AI creates.</strong></p></li><li><p><strong>Use multimodal AI to combine text, image, video, and more.</strong></p></li><li><p><strong>Learn prompt engineering like a skill &#8212; it pays off.</strong></p></li><li><p><strong>Pick the right LLM for your task.</strong></p></li><li><p><strong>The best AI is the one you know how to use effectively.</strong></p></li></ul><div><hr></div><p>Thanks a reading, I hope this was helpful.</p><h2><strong>&#128075; Let&#8217;s connect</strong></h2><blockquote><p>You can find me on <strong><a href="https://www.linkedin.com/in/sanjay-mehta-475280176/">LinkedIn</a></strong>.</p><p><em>If you like my content don&#8217;t forget to subscribe and hit the like </em>&#10084;&#65039;<em> button at the bottom to help support me or share this with a friend. It keeps me motivated to share more content and help people to learn more. </em>&#128591;</p></blockquote><p></p><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://sanjayofficial.substack.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">Thanks for reading Tech Newsletter! Subscribe for free to receive new posts and support my work.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div><div class="captioned-button-wrap" data-attrs="{&quot;url&quot;:&quot;https://sanjayofficial.substack.com/p/generative-ai-in-a-nutshell-mastering?utm_source=substack&utm_medium=email&utm_content=share&action=share&quot;,&quot;text&quot;:&quot;Share&quot;}" data-component-name="CaptionedButtonToDOM"><div class="preamble"><p class="cta-caption">Thanks for reading Tech Newsletter! This post is public so feel free to share it.</p></div><p class="button-wrapper" data-attrs="{&quot;url&quot;:&quot;https://sanjayofficial.substack.com/p/generative-ai-in-a-nutshell-mastering?utm_source=substack&utm_medium=email&utm_content=share&action=share&quot;,&quot;text&quot;:&quot;Share&quot;}" data-component-name="ButtonCreateButton"><a class="button primary" href="https://sanjayofficial.substack.com/p/generative-ai-in-a-nutshell-mastering?utm_source=substack&utm_medium=email&utm_content=share&action=share"><span>Share</span></a></p></div><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p>]]></content:encoded></item><item><title><![CDATA[Building Blocks You Must Know to Solve Any System Design Problem]]></title><description><![CDATA[The essential technologies every engineer should master for designing scalable, reliable systems.]]></description><link>https://sanjayofficial.substack.com/p/building-blocks-you-must-know-to</link><guid isPermaLink="false">https://sanjayofficial.substack.com/p/building-blocks-you-must-know-to</guid><dc:creator><![CDATA[Sanjay Mehta]]></dc:creator><pubDate>Sat, 26 Apr 2025 12:01:18 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!qh67!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8b868015-2432-47ce-98a5-e66541260182_1280x720.heic" length="0" type="image/jpeg"/><content:encoded><![CDATA[<div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!qh67!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8b868015-2432-47ce-98a5-e66541260182_1280x720.heic" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!qh67!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8b868015-2432-47ce-98a5-e66541260182_1280x720.heic 424w, https://substackcdn.com/image/fetch/$s_!qh67!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8b868015-2432-47ce-98a5-e66541260182_1280x720.heic 848w, https://substackcdn.com/image/fetch/$s_!qh67!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8b868015-2432-47ce-98a5-e66541260182_1280x720.heic 1272w, https://substackcdn.com/image/fetch/$s_!qh67!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8b868015-2432-47ce-98a5-e66541260182_1280x720.heic 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!qh67!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8b868015-2432-47ce-98a5-e66541260182_1280x720.heic" width="1280" height="720" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/8b868015-2432-47ce-98a5-e66541260182_1280x720.heic&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:720,&quot;width&quot;:1280,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:115841,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/heic&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:&quot;https://sanjayofficial.substack.com/i/162189444?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8b868015-2432-47ce-98a5-e66541260182_1280x720.heic&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!qh67!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8b868015-2432-47ce-98a5-e66541260182_1280x720.heic 424w, https://substackcdn.com/image/fetch/$s_!qh67!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8b868015-2432-47ce-98a5-e66541260182_1280x720.heic 848w, https://substackcdn.com/image/fetch/$s_!qh67!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8b868015-2432-47ce-98a5-e66541260182_1280x720.heic 1272w, https://substackcdn.com/image/fetch/$s_!qh67!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8b868015-2432-47ce-98a5-e66541260182_1280x720.heic 1456w" sizes="100vw" fetchpriority="high"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p></p><h2>1. Relational Databases</h2><p>Relational databases are structured, reliable, and perfect for scenarios where <strong>relationships between data</strong> are important.</p><h3>Key Features:</h3><ul><li><p><strong>SQL Joins</strong></p><ul><li><p>Joins allow you to combine data across multiple tables.</p></li><li><p><strong>Caution</strong>: They can become major performance bottlenecks, especially at scale. Use wisely!</p></li></ul></li><li><p><strong>Indexes</strong></p><ul><li><p>Indexes speed up queries by organizing data using <strong>B-Trees</strong> or <strong>Hash Tables</strong>.</p></li><li><p>Common types:</p><ul><li><p>Multi-column indexes</p></li><li><p>Geospatial indexes</p></li><li><p>Full-text indexes</p></li></ul></li><li><p><strong>Trade-off</strong>: More indexes = Faster reads but <strong>slower writes</strong>.</p><p></p></li></ul></li><li><p><strong>Transactions</strong></p><ul><li><p>Transactions group multiple operations into <strong>a single atomic unit</strong>.</p></li><li><p>Locking Models:</p><ul><li><p><strong>Pessimistic Locking</strong>: Prioritizes <strong>accuracy</strong> (good for critical financial systems).</p></li><li><p><strong>Optimistic Locking</strong>: Prioritizes <strong>performance</strong> (good for high-concurrency environments).</p></li></ul></li></ul></li></ul><h3>Examples:</h3><ul><li><p><strong>PostgreSQL</strong></p></li><li><p><strong>MySQL</strong></p><p></p></li></ul><div><hr></div><h2>2. NoSQL Databases</h2><p>NoSQL databases offer <strong>flexibility, scalability</strong>, and are ideal for <strong>dynamic, high-velocity data</strong>.</p><h3>Key Features:</h3><ul><li><p><strong> Data Models</strong></p><ul><li><p>NoSQL comes in different flavors:</p><ul><li><p><strong>Key-Value Stores</strong> (e.g., Redis, DynamoDB)</p></li><li><p><strong>Document Stores</strong> (e.g., MongoDB)</p></li><li><p><strong>Column-Family Stores</strong> (e.g., Cassandra)</p></li><li><p><strong>Graph Databases</strong> (e.g., Neo4j)</p></li></ul></li></ul></li><li><p><strong>Consistency Models</strong><br>Understand different types of consistency guarantees:</p><ul><li><p><strong>Strong Consistency</strong>: Always the latest data.</p></li><li><p><strong>Causal Consistency</strong>: Cause-effect order maintained.</p></li><li><p><strong>Sequential Consistency</strong>: Same order for all users.</p></li><li><p><strong>Read-Your-Writes Consistency</strong>: You see your changes immediately.</p></li><li><p><strong>Eventual Consistency</strong>: Data will become consistent... eventually.</p></li></ul></li><li><p><strong>Indexing</strong></p><ul><li><p>NoSQL also supports indexes (B-Trees, Hash Indexes) to speed up queries.</p></li></ul></li><li><p><strong>Scalability</strong></p><ul><li><p>Designed for <strong>horizontal scaling</strong>.</p></li><li><p>Techniques:</p><ul><li><p><strong>Consistent Hashing</strong></p></li><li><p><strong>Sharding</strong> (splitting data across nodes)</p></li></ul></li></ul></li></ul><h3>Examples:</h3><ul><li><p><strong>DynamoDB</strong></p></li><li><p><strong>Cassandra</strong></p></li><li><p><strong>MongoDB</strong></p></li></ul><div><hr></div><h2>3. Blob Storage</h2><p><strong>Blob = Binary Large Object</strong> &#8212; Think images, videos, backups.</p><h3>Key Features:</h3><ul><li><p>Designed to store <strong>large, unstructured files</strong> efficiently.</p></li><li><p>Supports <strong>versioning</strong>, <strong>lifecycle management</strong>, and <strong>access control</strong>.</p></li></ul><h3>Use Cases:</h3><ul><li><p>Storing user-uploaded media (profile pictures, videos).</p></li><li><p>System backups and archival.</p></li></ul><h3>Examples:</h3><ul><li><p>Amazon S3</p></li><li><p>Google Cloud Storage</p></li><li><p>Azure Blob Storage</p></li></ul><div><hr></div><h2>4. Search Optimized Storage</h2><p>When you need <strong>fast and flexible querying</strong> over large datasets.</p><h3>Key Features:</h3><ul><li><p>Full-text search</p></li><li><p>Faceted search (filtering, sorting)</p></li><li><p>Distributed indexing and querying.</p></li></ul><h3>Use Cases:</h3><ul><li><p>Building search bars, product catalogs, document retrieval.</p></li></ul><h3>Examples:</h3><ul><li><p>Elasticsearch</p></li><li><p>Apache Solr</p></li><li><p>OpenSearch</p></li></ul><div><hr></div><h2>5. API Gateway</h2><p>Acts as the <strong>single entry point</strong> for external clients.</p><h3>Key Features:</h3><ul><li><p>Request routing and load distribution.</p></li><li><p>Authentication and authorization.</p></li><li><p>Rate limiting and throttling.</p></li><li><p>API version management.</p></li></ul><h3>Use Cases:</h3><ul><li><p>Managing access to microservices.</p></li><li><p>Centralized security enforcement.</p></li></ul><h3>Examples:</h3><ul><li><p>AWS API Gateway</p></li><li><p>Kong</p></li><li><p>Apigee</p></li></ul><div><hr></div><h2>6. Load Balancer</h2><p>Distributes traffic across multiple servers for <strong>scalability</strong> and <strong>high availability</strong>.</p><h3>Key Features:</h3><ul><li><p>Health checks and failover</p></li><li><p>SSL termination</p></li><li><p>Sticky sessions (session affinity)</p></li></ul><h3>Use Cases:</h3><ul><li><p>Handling millions of concurrent users.</p></li><li><p>Redundancy and uptime guarantees.</p></li></ul><h3>Examples:</h3><ul><li><p>AWS Elastic Load Balancer (ELB)</p></li><li><p>Nginx</p></li><li><p>HAProxy</p></li></ul><div><hr></div><h2>7. Queue</h2><p>Enables <strong>asynchronous communication</strong> between services.</p><h3>Key Features:</h3><ul><li><p>Message durability</p></li><li><p>Message acknowledgment and retries</p></li><li><p>Dead-letter queues (handling failed messages)</p></li></ul><h3>Use Cases:</h3><ul><li><p>Email sending</p></li><li><p>Background job processing</p></li><li><p>Task offloading</p></li></ul><h3>Examples:</h3><ul><li><p>RabbitMQ</p></li><li><p>Amazon SQS</p></li><li><p>ActiveMQ</p></li></ul><div><hr></div><h2>8. Stream</h2><p>Handles <strong>real-time, high-throughput</strong> data processing.</p><h3>Key Features:</h3><ul><li><p>Ordered, replayable event logs</p></li><li><p>Partitioning for horizontal scaling</p></li><li><p>Consumer groups for parallel processing</p></li></ul><h3>Use Cases:</h3><ul><li><p>Analytics pipelines</p></li><li><p>Monitoring systems</p></li><li><p>Real-time feed updates</p></li></ul><h3>Examples:</h3><ul><li><p>Apache Kafka</p></li><li><p>Amazon Kinesis</p></li></ul><div><hr></div><h2>9. Distributed Lock</h2><p>Ensures <strong>exclusive access</strong> to a resource across a distributed system.</p><h3>Key Features:</h3><ul><li><p>Prevents race conditions and data corruption.</p></li><li><p>Lease expiration to avoid deadlocks.</p></li></ul><h3>Use Cases:</h3><ul><li><p>Cron job scheduling across multiple servers.</p></li><li><p>Single-writer guarantees in distributed systems.</p></li></ul><h3>Examples:</h3><ul><li><p>Redlock algorithm (using Redis)</p></li><li><p>Zookeeper locks</p></li><li><p>etcd locks</p></li></ul><div><hr></div><h2>10. Distributed Cache</h2><p>Ultra-fast, <strong>low-latency</strong> data access layer.</p><h3>Key Features:</h3><ul><li><p>Data replication and partitioning.</p></li><li><p>TTL (Time-to-Live) for cache expiry.</p></li><li><p>Cache invalidation strategies.</p></li></ul><h3>Use Cases:</h3><ul><li><p>Session storage</p></li><li><p>Caching database query results</p></li><li><p>Leaderboard generation</p></li></ul><h3>Examples:</h3><ul><li><p>Redis</p></li><li><p>Memcached</p></li><li><p>Hazelcast</p></li></ul><div><hr></div><h2>11. Content Delivery Network (CDN)</h2><p>Globally distributes static content to users.</p><h3>Key Features:</h3><ul><li><p>Edge caching</p></li><li><p>DDoS protection</p></li><li><p>TLS termination</p></li></ul><h3>Use Cases:</h3><ul><li><p>Faster webpage load times.</p></li><li><p>Video streaming.</p></li><li><p>Static assets (JS, CSS, Images).</p></li></ul><h3>Examples:</h3><ul><li><p>Cloudflare</p></li><li><p>AWS CloudFront</p></li><li><p>Akamai</p><p></p></li></ul><div><hr></div><h2>Summary</h2><ul><li><p><strong>Databases</strong> manage structured data.</p></li><li><p><strong>Blob Storage</strong> manages large unstructured files.</p></li><li><p><strong>Queues and Streams</strong> handle async and real-time processing.</p></li><li><p><strong>Load Balancers and API Gateways</strong> manage traffic and entry points.</p></li><li><p><strong>Distributed Caches and Locks</strong> ensure speed and consistency.</p></li><li><p><strong>CDNs</strong> push content closer to your users.</p></li></ul><p>By deeply understanding these components, you can design scalable, efficient, and production-ready systems &#8212; no matter how big the challenge.</p><div><hr></div><p>Thanks a reading, I hope this was helpful.</p><h2>&#128075; Let&#8217;s connect</h2><blockquote><p>You can find me on <strong><a href="https://www.linkedin.com/in/sanjay-mehta-475280176/">LinkedIn</a></strong>.</p><p><em>If you like my content don&#8217;t forget to subscribe and hit the like </em>&#10084;&#65039;<em> button at the bottom to help support me or share this with a friend. It keeps me motivated to share more content and help people to learn more. </em>&#128591;</p></blockquote><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://sanjayofficial.substack.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">Thanks for reading Tech Newsletter! Subscribe  for free to receive new posts and support my work.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div><div class="captioned-button-wrap" data-attrs="{&quot;url&quot;:&quot;https://sanjayofficial.substack.com/p/building-blocks-you-must-know-to?utm_source=substack&utm_medium=email&utm_content=share&action=share&quot;,&quot;text&quot;:&quot;Share&quot;}" data-component-name="CaptionedButtonToDOM"><div class="preamble"><p class="cta-caption">This post is public so feel free to share it.</p></div><p class="button-wrapper" data-attrs="{&quot;url&quot;:&quot;https://sanjayofficial.substack.com/p/building-blocks-you-must-know-to?utm_source=substack&utm_medium=email&utm_content=share&action=share&quot;,&quot;text&quot;:&quot;Share&quot;}" data-component-name="ButtonCreateButton"><a class="button primary" href="https://sanjayofficial.substack.com/p/building-blocks-you-must-know-to?utm_source=substack&utm_medium=email&utm_content=share&action=share"><span>Share</span></a></p></div><p></p><p></p><p></p><p></p>]]></content:encoded></item><item><title><![CDATA[Refactoring for the Future: Improving Code Without Changing Behavior]]></title><description><![CDATA[Writing Clean, Maintainable Code Through Refactoring]]></description><link>https://sanjayofficial.substack.com/p/refactoring-for-the-future-improving</link><guid isPermaLink="false">https://sanjayofficial.substack.com/p/refactoring-for-the-future-improving</guid><dc:creator><![CDATA[Sanjay Mehta]]></dc:creator><pubDate>Tue, 25 Mar 2025 10:00:37 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!WmlO!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3c673c11-1632-4255-b03f-5dd3394544ea_1422x800.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!WmlO!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3c673c11-1632-4255-b03f-5dd3394544ea_1422x800.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!WmlO!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3c673c11-1632-4255-b03f-5dd3394544ea_1422x800.png 424w, https://substackcdn.com/image/fetch/$s_!WmlO!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3c673c11-1632-4255-b03f-5dd3394544ea_1422x800.png 848w, https://substackcdn.com/image/fetch/$s_!WmlO!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3c673c11-1632-4255-b03f-5dd3394544ea_1422x800.png 1272w, https://substackcdn.com/image/fetch/$s_!WmlO!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3c673c11-1632-4255-b03f-5dd3394544ea_1422x800.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!WmlO!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3c673c11-1632-4255-b03f-5dd3394544ea_1422x800.png" width="1422" height="800" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/3c673c11-1632-4255-b03f-5dd3394544ea_1422x800.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:800,&quot;width&quot;:1422,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:null,&quot;alt&quot;:&quot;Diagram showing red, green, refactor cycle. It marks refactor as done&quot;,&quot;title&quot;:null,&quot;type&quot;:null,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:null,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="Diagram showing red, green, refactor cycle. It marks refactor as done" title="Diagram showing red, green, refactor cycle. It marks refactor as done" srcset="https://substackcdn.com/image/fetch/$s_!WmlO!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3c673c11-1632-4255-b03f-5dd3394544ea_1422x800.png 424w, https://substackcdn.com/image/fetch/$s_!WmlO!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3c673c11-1632-4255-b03f-5dd3394544ea_1422x800.png 848w, https://substackcdn.com/image/fetch/$s_!WmlO!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3c673c11-1632-4255-b03f-5dd3394544ea_1422x800.png 1272w, https://substackcdn.com/image/fetch/$s_!WmlO!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3c673c11-1632-4255-b03f-5dd3394544ea_1422x800.png 1456w" sizes="100vw" fetchpriority="high"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><h3><strong>What is Refactoring?</strong></h3><p>Refactoring is the process of improving the internal structure of code without altering its external behavior.</p><h3><strong>Why Refactoring is important?</strong></h3><ul><li><p>Makes code easier to read and maintain.</p></li><li><p>Reduce Technical debt</p></li><li><p>Improves collaboration in teams.</p></li><li><p>Helps in scaling applications efficiently.</p></li></ul><h3><strong>When to Refactor?</strong></h3><ul><li><p>Before adding new features.</p></li><li><p>After identifying code smells.</p></li><li><p>During regular maintenance.</p></li></ul><div><hr></div><h3><strong>What are Code Smells?</strong></h3><p>These are the indicators of bad code. Some common ones:</p><ol><li><p><strong>Duplicated Code</strong>&nbsp;</p><p><em>Duplicated code</em> is one of the worst smells, whenever a change is made, one needs to check if this should have happened to just one or all of the existing copies of code, wherever they are.</p><p></p></li><li><p><strong>Long Method</strong>&nbsp;</p><p>A method is doing too much. Like the Hotel California, something is always being added to a method but nothing is ever taken out. Since it&#8217;s easier to write code than to read it, this &#8220;smell&#8221; remains unnoticed until the method turns into an ugly, oversized beast.</p><p></p></li><li><p><strong>Large Class</strong>&nbsp;</p><p>A class has too many responsibilities. It violates the single responsibility principle <strong>which states that a class should have only one reason to change.</strong> Many long-form methods and an abundant number of parameters that can be passed to a class cause <em>Large Class</em> problems.</p><p></p></li><li><p><strong>Divergent Change</strong></p><p>Multiple reasons to change a single class. If adding a simple feature makes the developer change many seemingly unrelated methods inside a class, that indicates the <em>Divergent Change</em> code smell.</p><p></p></li><li><p><strong>Shotgun Surgery</strong>&nbsp;</p><p>A single change requires modifications in multiple places. Similar to <strong>Divergent Change</strong>, but with a broader spectrum, the smell symptom of the <em>Shotgun Surgery</em> code is detected by the unnecessary requirement of changing multiple different classes to introduce a single modification.</p><p></p></li><li><p><strong>Feature Envy</strong>&nbsp;</p><p> A method uses more data from another class than its own.If a method inside a class manipulates more features (be it fields or methods) of another class more than from its own, then this method has a <em>Feature Envy</em>.</p><p>In <strong>Object-Oriented Programming</strong>, developers should tie the functionality and behavior close to the data it uses. Coupled objects have to be used together. </p><p></p></li><li><p><strong>Data Clumps</strong>&nbsp;</p><p>Groups of variables that always appear together. <em>Data Clumps</em> refer to a situation in which a few variables are passed around many times in the codebase instead of being packed into a separate object. Think of it as having to hold different groceries in a grocery store by hand instead of putting them into a basket.</p><p></p></li><li><p><strong>Primitive Obsession</strong>&nbsp;</p><p>Primitive Obsession is a <strong>code smell</strong> where primitive data types (e.g., int, string, boolean) are overused instead of creating domain-specific objects. This often leads to:</p><ul><li><p><strong>Scattered logic</strong> across the codebase</p></li><li><p><strong>Lack of encapsulation</strong></p></li><li><p><strong>High risk of errors</strong></p></li></ul><p></p></li><li><p><strong>Switch Statements</strong>&nbsp;</p><p>Long&nbsp;`if-else`&nbsp;or&nbsp;`switch`&nbsp;statements that could be replaced by polymorphism. It violates the <strong>Open Closed Principle</strong>, which states &#8220;Software entities (classes, modules, functions) should be open for extension, but closed for modification.&#8221;</p></li></ol><div><hr></div><h3>Refactoring Techniques</h3><p><em>Code</em> is a must-read for developers aiming to write better code. Here are<strong> </strong>the <strong>key refactoring techniques</strong> to fix the above code smells:</p><h4><strong>1. Extract Method</strong> </h4><p>Move a block of code into a separate method.</p><p>Extract Method comes under the category of <strong>Composing Methods (Improving Readability and Modularity) </strong>and this technique solves the problem of <strong>Duplicated Code</strong> and <strong>Long Method </strong>code smell<strong>.</strong></p><p><strong>Problem</strong></p><p>You have a code fragment that can be grouped together. The more lines found in a method, the harder it&#8217;s to figure out what the method does. </p><pre><code>void printOwing() {
  printBanner();
  System.out.println("name: " + name);
  System.out.println("amount: " + getOutstanding());
}</code></pre><p><strong>Solution</strong></p><p>Move this code to a separate new method (or function) and replace the old code with a call to the method.</p><pre><code>void printOwing() {
  printBanner();
  printDetails(getOutstanding());
}

void printDetails(double outstanding) {
  System.out.println("name: " + name);
  System.out.println("amount: " + outstanding);
}</code></pre><p><strong>Break large methods into smaller, well-named methods</strong> to improve readability, maintainability, and reusability!</p><h4><strong>2. Extract Class</strong></h4><p>Split a class into multiple classes when it has too many responsibilities.</p><p>Extract Class comes under the category of <strong>Moving Features Between Objects.</strong>This technique solves the problem of <strong>Duplicated Code</strong>, <strong>Long Class, Divergent Change and  Data Clumps </strong>code smell<strong>.</strong></p><p>This refactoring technique will help maintain adherence to the <em>Single Responsibility Principle</em>. The code of your classes will be more obvious and understandable.</p><p>Single-responsibility classes are more reliable and tolerant of changes. For example, say that you have a class responsible for ten different things. When you change this class to make it better for one thing, you risk breaking it for the nine others.</p><p><strong>Problem</strong></p><p>When one class does the work of two, awkwardness results.</p><pre><code>class Person {
   String name;
   String officeAreaCode;
   String officeNumber;

   getTelephoneNumber() {}
}  </code></pre><p><strong>Solution</strong></p><p>Instead, create a new class and place the fields and methods responsible for the relevant functionality in it.</p><pre><code>class Person {
   String name;
   TelephoneNumber telephoneNumber;
}  </code></pre><pre><code>class TelephoneNumber {
   String officeAreaCode;
   String officeNumber;

   getTelephoneNumber() {}
}</code></pre><p><strong>Break large classes into smaller, well-defined classes</strong> to improve <strong>modularity, readability, and maintainability</strong>!</p><h4><strong>3. Move Method</strong></h4><p>Shift a method to a more relevant class to improve cohesion.</p><p>Move method comes under the category of <strong>Moving Features Between Objects </strong>and<strong> t</strong>his technique solves the problem of <strong>Shotgun Surgery</strong> <strong>and</strong> <strong>Feature Envy </strong>code smell<strong>.</strong></p><p><strong>Problem</strong></p><p>Here, the <strong>BankService</strong> class is calculating the account balance, even though <strong>BankAccount</strong> has all the data.</p><pre><code>class BankAccount {
    private double balance;
    private double interestRate;

    public BankAccount(double balance, double interestRate) {
        this.balance = balance;
        this.interestRate = interestRate;
    }

    public double getBalance() {
        return balance;
    }

    public double getInterestRate() {
        return interestRate;
    }
}

class BankService {
    public double calculateInterest(BankAccount account) {
        return account.getBalance() * account.getInterestRate();
    }
}</code></pre><p><strong>Solution</strong></p><p>We move calculateInterest<code>()</code> to BankAccount so it <strong>encapsulates its own behavior</strong>.</p><pre><code>class BankAccount {
    private double balance;
    private double interestRate;

    public BankAccount(double balance, double interestRate) {
        this.balance = balance;
        this.interestRate = interestRate;
    }

    public double calculateInterest() { 
        return balance * interestRate;
    }
}

class BankService {
    public void printInterest(BankAccount account) {
        System.out.println("Interest: " + account.calculateInterest()); 
    }
}</code></pre><p>Always place behavior <strong>where the data lives</strong> to improve <strong>encapsulation and maintainability</strong>.</p><h4><strong>4. Replace Conditional with Polymorphism</strong></h4><p>Use object-oriented principles to eliminate long if-else or switch statements.</p><p>It comes under the category of <strong>Simplifying Conditional Expressions </strong>and this technique solves the problem of <strong>switch or if-else statements </strong>code smell<strong>.</strong></p><p><strong>Problem</strong></p><p>The <strong>Employee</strong> class uses a <strong>switch statement</strong> to determine salary calculations based on employee type.</p><pre><code>class Employee {
    private String type;

    public Employee(String type) {
        this.type = type;
    }

    public double calculateSalary(double baseSalary) {
        switch (type) {
            case "Manager":
                return baseSalary + 5000;
            case "Developer":
                return baseSalary + 2000;
            case "Intern":
                return baseSalary;
            default:
                throw new IllegalArgumentException("Unknown employee type");
        }
    }
}</code></pre><p><strong>Solution</strong></p><p>We <strong>replace the </strong>switch<strong> statement</strong> with <strong>inheritance and polymorphism</strong>.</p><pre><code>// Step 1: Create an abstract base class
abstract class Employee {
    public abstract double calculateSalary(double baseSalary);
}

// Step 2: Implement specific employee types
class Manager extends Employee {
    public double calculateSalary(double baseSalary) {
        return baseSalary + 5000;
    }
}

class Developer extends Employee {
    public double calculateSalary(double baseSalary) {
        return baseSalary + 2000;
    }
}

class Intern extends Employee {
    public double calculateSalary(double baseSalary) {
        return baseSalary;
    }
}

// Step 3: Use polymorphism in the main program
class Payroll {
    public static void main(String[] args) {
        Employee manager = new Manager();
        Employee developer = new Developer();
        Employee intern = new Intern();

        System.out.println("Manager Salary: " + manager.calculateSalary(50000));
        System.out.println("Developer Salary: " + developer.calculateSalary(50000));
        System.out.println("Intern Salary: " + intern.calculateSalary(50000));
    }
}</code></pre><p><strong>Use polymorphism</strong> - Replace conditionals (switch or if-else) statements with object-oriented design patterns like <strong>Strategy or Factory Patterns</strong> to make code <strong>scalable, maintainable, and extensible</strong>.</p><h4><strong>4. Value Objects</strong></h4><p>A <strong>Value Object (VO)</strong> is an <strong>immutable object</strong> that represents a concept <strong>without identity</strong> (e.g., money, coordinates, dates). Unlike entities, <strong>two Value Objects are considered equal if their values match</strong>.</p><p>It falls under the category of <strong>"Composing Methods"</strong> and <strong>"Simplifying Conditional Expressions" </strong>and<strong> </strong>this technique solves the problem of <strong>Primitive Obsession </strong>code smell.</p><p><strong>Problem - Using Primitives Directly</strong></p><pre><code>class Order {
    private String currency;
    private double amount;

    public Order(String currency, double amount) {
        this.currency = currency;
        this.amount = amount;
    }
}</code></pre><p><strong>Solution - Use Value Object</strong></p><pre><code>final class Money {
    private final double amount;
    private final String currency;

    public Money(double amount, String currency) {
        if (amount &lt; 0) throw new IllegalArgumentException("Amount cannot be negative");
        if (!currency.matches("USD|EUR|INR")) throw new IllegalArgumentException("Invalid currency");
        this.amount = amount;
        this.currency = currency;
    }
}

class Order {
    private Money totalPrice;

    public Order(Money totalPrice) {
        this.totalPrice = totalPrice;
    }
}</code></pre><p><strong>Encapsulation</strong> : Money handles validation.<br><strong>Eliminates primitive obsession</strong> : No raw strings for currency.</p><p><strong>Stop using primitives for domain concepts!</strong> Use <strong>Value Objects &amp; Encapsulation</strong> to make code <strong>robust &amp; maintainable</strong>.</p><div><hr></div><p>Thanks a lot, I hope this was helpful.</p><h2>&#128075; Let&#8217;s connect</h2><blockquote><p>You can find me on <strong><a href="https://www.linkedin.com/in/sanjay-mehta-475280176/">LinkedIn</a></strong>.</p><p><em>If you like my content don&#8217;t forget to subscribe and hit the like </em>&#10084;&#65039;<em> button at the bottom to help support me or share this with a friend. It keeps me motivated to share more content and help people to learn more. </em>&#128591;</p></blockquote><p></p><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://sanjayofficial.substack.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">Thanks for reading Tech Newsletter! Subscribe for free to receive new posts and support my work.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div><p></p>]]></content:encoded></item><item><title><![CDATA[React.memo vs useMemo ]]></title><description><![CDATA[Want to optimize performance of your application use memoization.]]></description><link>https://sanjayofficial.substack.com/p/reactmemo-vs-usememo</link><guid isPermaLink="false">https://sanjayofficial.substack.com/p/reactmemo-vs-usememo</guid><dc:creator><![CDATA[Sanjay Mehta]]></dc:creator><pubDate>Thu, 06 Feb 2025 07:35:24 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!ER40!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ffab1724e-b272-4ddd-b59b-89a41bdf0fa2_2228x1124.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!ER40!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ffab1724e-b272-4ddd-b59b-89a41bdf0fa2_2228x1124.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!ER40!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ffab1724e-b272-4ddd-b59b-89a41bdf0fa2_2228x1124.png 424w, https://substackcdn.com/image/fetch/$s_!ER40!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ffab1724e-b272-4ddd-b59b-89a41bdf0fa2_2228x1124.png 848w, https://substackcdn.com/image/fetch/$s_!ER40!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ffab1724e-b272-4ddd-b59b-89a41bdf0fa2_2228x1124.png 1272w, https://substackcdn.com/image/fetch/$s_!ER40!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ffab1724e-b272-4ddd-b59b-89a41bdf0fa2_2228x1124.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!ER40!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ffab1724e-b272-4ddd-b59b-89a41bdf0fa2_2228x1124.png" width="1456" height="735" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/fab1724e-b272-4ddd-b59b-89a41bdf0fa2_2228x1124.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:735,&quot;width&quot;:1456,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:319806,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:null,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!ER40!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ffab1724e-b272-4ddd-b59b-89a41bdf0fa2_2228x1124.png 424w, https://substackcdn.com/image/fetch/$s_!ER40!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ffab1724e-b272-4ddd-b59b-89a41bdf0fa2_2228x1124.png 848w, https://substackcdn.com/image/fetch/$s_!ER40!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ffab1724e-b272-4ddd-b59b-89a41bdf0fa2_2228x1124.png 1272w, https://substackcdn.com/image/fetch/$s_!ER40!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ffab1724e-b272-4ddd-b59b-89a41bdf0fa2_2228x1124.png 1456w" sizes="100vw" fetchpriority="high"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>In my earlier post, I have discussed the main differences between <strong><a href="https://sanjayofficial.substack.com/p/usecallback-vs-usememo?r=1tkdkn">useCallback and useMemo</a></strong> and both are used for optimizing the performance of the React application. Similarly to that, React.memo is another component that is also used for improving the performance of the React application.</p><div><hr></div><h3><strong>What is Memoization?</strong></h3><p>Memoization is not the new concept in computer science, it is used in various context, mainly in <strong>dynamic programming</strong> to cache the result for the same input in the recursion, so we don&#8217;t need to call the expensive recursive method again to calculate the same value that we have encountered earlier and it will helps us to reduce the time complexity of the function and improve the overall performance of the system.</p><p><strong>Memoization</strong> ensures that a method doesn't run for the same inputs more than once by keeping a record of the results for the given inputs (usually in a hash map).</p><p>In React functional components, when props within a component change, the entire component re-renders by calling <strong>updateDOM</strong> function( <strong><a href="https://open.substack.com/pub/sanjayofficial/p/coming-soon?r=1tkdkn&amp;utm_campaign=post&amp;utm_medium=web&amp;showWelcomeOnShare=false">Refer - What will happen when you call the setState function</a></strong><a href="https://open.substack.com/pub/sanjayofficial/p/coming-soon?r=1tkdkn&amp;utm_campaign=post&amp;utm_medium=web&amp;showWelcomeOnShare=false"> </a>). In other words, if any value within a component updates, the entire component will re-render, including functions/components that have not had their values/props altered.</p><blockquote><p>Now, with the new version of <strong>React 19</strong>, we don&#8217;t need to do <strong>memoization</strong> anymore in our code, React will take care of optimizations using <strong><a href="https://react.dev/learn/react-compiler">React Compiler</a></strong>, a new feature introduced in <strong>React 19</strong>.</p></blockquote><div><hr></div><h3>React.memo</h3><p> <strong>memo</strong> lets you skip re-rendering a component when its props are unchanged.</p><pre><code>const MemoizedComponent = memo(SomeComponent, arePropsEqual?)</code></pre><h4><strong>Parameters</strong></h4><ul><li><p> The first parameter is the component that you want to memoize. The <strong>memo</strong> does not modify this component, but returns a new, memoized component instead. Any valid React component, including functions and <strong>forwardRef</strong> components, is accepted.</p></li><li><p>The second parameter is <strong>optional</strong> : A function that accepts two arguments: the component&#8217;s previous props, and its new props. It should return true if the old and new props are equal: that is, if the component will render the same output and behave in the same way with the new props as with the old. Otherwise it should return false. Usually, you will not specify this function. By default, React will compare each prop with Object.is.</p></li></ul><h4><strong>Returns</strong></h4><p><strong>memo</strong> returns a new React component. It behaves the same as the component provided to <strong>memo</strong> except that React will not always re-render it when its parent is being re-rendered unless its props have changed.</p><h4>Example - MemoizedProduct Component </h4><pre><code>import { ProductType } from "../context/ProductsProvider"
import { ReducerActionType, ReducerAction } from "../context/CartProvider"
import { ReactElement, memo } from "react"

type <strong>ProductProps</strong> = {
    product : ProductType,
    dispatch : React.Dispatch&lt;ReducerAction&gt;,
    REDUCER_ACTIONS : ReducerActionType
}

const <strong>Product</strong> = ({product, dispatch, REDUCER_ACTIONS} : ProductProps) : ReactElement =&gt; {
   const relativePath = "../images/" + product.sku + '.jpg';
   const img: string = new URL(relativePath, import.meta.url).href

   const onAddToCart = () =&gt; dispatch({type : REDUCER_ACTIONS.ADD , payload : {...product , qty : 1}});

   const itemInCart = inCart ? ' Item in Cart ': null

   const content = &lt;article className="product"&gt;
        &lt;h3&gt;{product.name}&lt;/h3&gt;
        &lt;img src={img} alt={product.name} className="product__img"/&gt;
        &lt;p&gt;{new Intl.NumberFormat('en-US', { style : 'currency', currency : 'USD' }).format(product.price)}
        {itemInCart}&lt;/p&gt;
        &lt;button onClick={onAddToCart}&gt;Add to Cart&lt;/button&gt;
   &lt;/article&gt;

    return content;
}

function <strong>areProductsEqual</strong>({product : prevProduct} : ProductProps,{product : nextProduct} : ProductProps) {
    return Object.keys(prevProduct).every(key =&gt; {
        return prevProduct[key as keyof ProductType] === nextProduct[key as keyof ProductType]
    }) 
}

const <strong>MemoizedProduct</strong> = <strong>memo</strong>&lt;typeof Product&gt;(<strong>Product</strong>, <strong>areProductsEqual</strong>)

export default <strong>MemoizedProduct</strong></code></pre><div><hr></div><h3>useMemo</h3><p><strong>useMemo</strong> is a React Hook that lets you <strong>cache the result of a calculation</strong> between re-renders.</p><p>Same as useCallback, we should define the <strong>useMemo</strong> at the top level of the component.</p><pre><code><code>const memoizedValue = useMemo(() =&gt; expensiveFunction(), [dependency]);</code></code></pre><h3>Parameters:</h3><ul><li><p>The first argument is the function <strong>calculating the value that you want to cache</strong>. It should be pure, should take no arguments, and should return a value of any type. <strong>React will call your function during the initial render.</strong></p></li><li><p>The second argument is an array of dependencies that determines when the value should be recalculated. React will return the same value again if the <strong>dependencies</strong> have not changed since the last render. Otherwise, it will call the function, return its result, and store it so it can be reused later. React will compare each dependency with its previous value using the <strong>Object.is</strong> comparison.</p></li></ul><h4><strong>Example 1: useMemo without dependency.</strong></h4><pre><code><code>import React, { useState, useMemo } from 'react';

const ExpensiveComponent = () =&gt; {
    const [count, setCount] = useState(0);

    const computedValue = useMemo(() =&gt; {
        console.log("Computing expensive value...");
        return count * 2;
    }, []); 

    return (
        &lt;div&gt;
            &lt;h1&gt;Computed Value: {computedValue}&lt;/h1&gt;
            &lt;p&gt;Count: {count}&lt;/p&gt;
            &lt;button onClick={() =&gt; setCount(count + 1)}&gt;Increment   Count&lt;/button&gt;
      &lt;/div&gt;
    );
};

export default ExpensiveComponent;</code></code></pre><p>In this example, we are passing dependencies as an empty array, that means caching a value that should only be computed once.</p><h4><strong>Example 2: useMemo with dependency.</strong></h4><pre><code><code>import React, { useState, useMemo } from 'react';

const ExpensiveComponent = () =&gt; {
    const [count, setCount] = useState(0);
    const [items, setItems] = useState([1, 2, 3, 4, 5]);

    const expensiveCalculation = (items) =&gt; {
        console.log("Calculating...");
        return items.reduce((sum, item) =&gt; sum + item, 0);
    };

    const memoizedCalculation = useMemo(() =&gt; expensiveCalculation(items), [items]);

    return (
        &lt;div&gt;
            &lt;h1&gt;Expensive Calculation Example&lt;/h1&gt;
            &lt;p&gt;Sum of items: {memoizedCalculation}&lt;/p&gt;
            &lt;button onClick={() =&gt; setCount(count + 1)}&gt;Increment Count&lt;/button&gt;
            &lt;button onClick={() =&gt; setItems([...items, Math.random()])}&gt;Add Random Item&lt;/button&gt;
        &lt;/div&gt;
    );
};

export default ExpensiveComponent;</code></code></pre><p>In this example, dependency is on <strong>items, </strong>so function will be called again to calculate a new value when items state updates.</p><div><hr></div><h3><strong>Differences between </strong><code>useMemo</code><strong> and </strong><code>memo.</code></h3><p>Let's summarize the differences between the two:</p><ul><li><p><strong>Purpose : useMemo</strong> caches the return value of a function whereas <strong>memo</strong> caches the component.</p></li><li><p><strong>When to use : useMemo</strong> is used when you have an expensive calculation you want to avoid on every render. <strong>memo</strong> is used to cache the component to avoid re-rendering.</p></li><li><p><strong>Dependencies : useMemo</strong> makes sure that an expensive function should only be called for changed dependencies. <strong>memo</strong> re-renders the component when the dependencies change.</p></li><li><p><strong>Common use case : useMemo </strong>hook<strong> </strong>cache results of expensive calculations or data processing. Wrap a component in <strong>memo</strong> to get a <em>memoized</em> version of that component.</p></li></ul><blockquote><p><strong>Memoization is a performance optimization, not a guarantee</strong>. React may still re-render the memoized version of your component.</p></blockquote><div><hr></div><h3><strong>Summary:</strong></h3><ul><li><p><strong>useMemo</strong> memoizes the <strong>result</strong> of an expensive computation and only recomputes it when the <strong>dependencies</strong> change.</p></li><li><p><strong>memo </strong>memoizes the <strong>component usually child component</strong> and only re-renders the component when the <strong>dependencies</strong> change.</p></li><li><p><strong>useMemo </strong>is useful for avoiding expensive recalculations on every render.</p></li><li><p><strong>memo </strong>is useful for avoiding re-rendering the component on every render.</p></li><li><p>You should only use <strong>useMemo</strong> and <strong>memo</strong> it for <strong>performance optimizations</strong> when you notice performance bottlenecks.</p></li><li><p>Using <strong>memo </strong>is not a guarantee, React may still re-render the memoized version of your component.</p></li></ul><div><hr></div><p>In the upcoming post, we will discuss more about new features of <strong>React 19</strong> like <strong>useFormStatus</strong> hook and <strong>React compiler.</strong> </p><p>Stay tuned! Thanks for reading.</p><h2>&#128075; Let&#8217;s connect</h2><blockquote><p>You can find me on <strong><a href="https://www.linkedin.com/in/sanjay-mehta-475280176/">LinkedIn</a></strong>.</p><p><em>If you like my content don&#8217;t forget to subscribe and hit the like </em>&#10084;&#65039;<em> button at the bottom to help support me or share this with a friend. It keeps me motivated to share more content and help people to learn more. </em>&#128591;</p></blockquote><p></p><p class="button-wrapper" data-attrs="{&quot;url&quot;:&quot;https://sanjayofficial.substack.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe now&quot;,&quot;action&quot;:null,&quot;class&quot;:null}" data-component-name="ButtonCreateButton"><a class="button primary" href="https://sanjayofficial.substack.com/subscribe?"><span>Subscribe now</span></a></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p>]]></content:encoded></item><item><title><![CDATA[useCallback vs useMemo]]></title><description><![CDATA[You should only rely on useMemo or useCallback hook as a performace optimization.]]></description><link>https://sanjayofficial.substack.com/p/usecallback-vs-usememo</link><guid isPermaLink="false">https://sanjayofficial.substack.com/p/usecallback-vs-usememo</guid><dc:creator><![CDATA[Sanjay Mehta]]></dc:creator><pubDate>Mon, 03 Feb 2025 20:41:52 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!WqNH!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F944a9469-e5c5-4cb6-9037-94f70260a8e7_1024x620.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!WqNH!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F944a9469-e5c5-4cb6-9037-94f70260a8e7_1024x620.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!WqNH!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F944a9469-e5c5-4cb6-9037-94f70260a8e7_1024x620.png 424w, https://substackcdn.com/image/fetch/$s_!WqNH!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F944a9469-e5c5-4cb6-9037-94f70260a8e7_1024x620.png 848w, https://substackcdn.com/image/fetch/$s_!WqNH!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F944a9469-e5c5-4cb6-9037-94f70260a8e7_1024x620.png 1272w, https://substackcdn.com/image/fetch/$s_!WqNH!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F944a9469-e5c5-4cb6-9037-94f70260a8e7_1024x620.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!WqNH!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F944a9469-e5c5-4cb6-9037-94f70260a8e7_1024x620.png" width="728" height="440.78125" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/944a9469-e5c5-4cb6-9037-94f70260a8e7_1024x620.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:false,&quot;imageSize&quot;:&quot;normal&quot;,&quot;height&quot;:620,&quot;width&quot;:1024,&quot;resizeWidth&quot;:728,&quot;bytes&quot;:null,&quot;alt&quot;:&quot;&quot;,&quot;title&quot;:null,&quot;type&quot;:null,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:null,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" title="" srcset="https://substackcdn.com/image/fetch/$s_!WqNH!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F944a9469-e5c5-4cb6-9037-94f70260a8e7_1024x620.png 424w, https://substackcdn.com/image/fetch/$s_!WqNH!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F944a9469-e5c5-4cb6-9037-94f70260a8e7_1024x620.png 848w, https://substackcdn.com/image/fetch/$s_!WqNH!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F944a9469-e5c5-4cb6-9037-94f70260a8e7_1024x620.png 1272w, https://substackcdn.com/image/fetch/$s_!WqNH!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F944a9469-e5c5-4cb6-9037-94f70260a8e7_1024x620.png 1456w" sizes="100vw" fetchpriority="high"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>In this post, we are going to discuss useCallback and useMemo hooks and the differences between them.</p><div><hr></div><h2><strong>The useCallback Hook</strong></h2><p><strong>useCallback</strong> is a React Hook that lets you <strong>cache a function definition</strong> between re-renders.</p><p>Like every hook, we need to define at the top level of the component, you should define the <strong>useCallback</strong> at the top level of your component.</p><pre><code>const memoizedCallback = useCallback(() =&gt; {
    // callback logic here
}, [dependencies]);</code></pre><h3>Parameters:</h3><ul><li><p>The first argument is the function value that you want to cache. It can take any arguments and return any values. React will return (not call!) your function back to you during the initial render. The function is returned to you so you can decide when and whether to call it.</p></li><li><p>The second argument is an array of dependencies that determines when the function should be recreated. React will give you the same function again if the dependencies have not changed since the last render. Otherwise, it will recreate the function and store it in case it can be reused later.</p></li></ul><h4><strong>Example 1: useCallback without dependency.</strong></h4><pre><code>import React, { useState, useCallback } from 'react';

const Counter = () =&gt; {
    const [count, setCount] = useState(0);

    const increment = useCallback(() =&gt; {
        setCount(prevCount =&gt; prevCount + 1);
    }, []);

    return (
        &lt;div&gt;
            &lt;p&gt;Count: {count}&lt;/p&gt;
            &lt;button onClick={increment}&gt;Increment&lt;/button&gt;
        &lt;/div&gt;
    );
};</code></pre><p>In this example, we are passing dependencies as an empty array, that means the function is only created once.</p><h4><strong>Example 2: useCallback with dependencies.</strong></h4><pre><code>import React, { useState, useCallback } from 'react';

const Counter = () =&gt; {
    const [count, setCount] = useState(0);
    const [name, setName] = useState("React");

    const increment = useCallback(() =&gt; {
        setCount(prevCount =&gt; prevCount + 1);
        console.log(`Count updated: ${count}`);
    }, [count]); 

    const changeName = () =&gt; {
        setName(name === "React" ? "Vite" : "React");
    };

    return (
        &lt;div&gt;
            &lt;h1&gt;{name} Counter&lt;/h1&gt;
            &lt;p&gt;Current Count: {count}&lt;/p&gt;
            &lt;button onClick={increment}&gt;Increment&lt;/button&gt;
            &lt;button onClick={changeName}&gt;Change Name&lt;/button&gt;
       &lt;/div&gt;
    );
};

export default Counter;</code></pre><p>In this example, dependency is on <strong>count, </strong>so function will only recreates when count updates.</p><div><hr></div><h2><strong>The useMemo Hook</strong></h2><p><strong>useMemo</strong> is a React Hook that lets you <strong>cache the result of a calculation</strong> between re-renders.</p><p>Same as useCallback, we should define the <strong>useMemo</strong> at the top level of the component.</p><pre><code>const memoizedValue = useMemo(() =&gt; expensiveFunction(), [dependency]);</code></pre><h3>Parameters:</h3><ul><li><p>The first argument is the function <strong>calculating the value that you want to cache</strong>. It should be pure, should take no arguments, and should return a value of any type. <strong>React will call your function during the initial render.</strong> </p></li><li><p>The second argument is an array of dependencies that determines when the value  should be recalculated. React will return the same value again if the <strong>dependencies</strong> have not changed since the last render. Otherwise, it will call the function, return its result, and store it so it can be reused later. React will compare each dependency with its previous value using the <strong>Object.is</strong> comparison.</p></li></ul><h4><strong>Example 1: useMemo without dependency.</strong></h4><pre><code>import React, { useState, useMemo } from 'react';

const ExpensiveComponent = () =&gt; {
    const [count, setCount] = useState(0);

    const computedValue = useMemo(() =&gt; {
        console.log("Computing expensive value...");
        return count * 2;
    }, []); 

    return (
        &lt;div&gt;
            &lt;h1&gt;Computed Value: {computedValue}&lt;/h1&gt;
            &lt;p&gt;Count: {count}&lt;/p&gt;
            &lt;button onClick={() =&gt; setCount(count + 1)}&gt;Increment   Count&lt;/button&gt;
      &lt;/div&gt;
    );
};

export default ExpensiveComponent;</code></pre><p>In this example, we are passing dependencies as an empty array, that means caching a value that should only be computed once.</p><h4><strong>Example 2: useMemo with dependency.</strong></h4><pre><code>import React, { useState, useMemo } from 'react';

const ExpensiveComponent = () =&gt; {
    const [count, setCount] = useState(0);
    const [items, setItems] = useState([1, 2, 3, 4, 5]);

    const expensiveCalculation = (items) =&gt; {
        console.log("Calculating...");
        return items.reduce((sum, item) =&gt; sum + item, 0);
    };

    const memoizedCalculation = useMemo(() =&gt; expensiveCalculation(items), [items]);

    return (
        &lt;div&gt;
            &lt;h1&gt;Expensive Calculation Example&lt;/h1&gt;
            &lt;p&gt;Sum of items: {memoizedCalculation}&lt;/p&gt;
            &lt;button onClick={() =&gt; setCount(count + 1)}&gt;Increment Count&lt;/button&gt;
            &lt;button onClick={() =&gt; setItems([...items, Math.random()])}&gt;Add Random Item&lt;/button&gt;
        &lt;/div&gt;
    );
};

export default ExpensiveComponent;</code></pre><p>In this example, dependency is on <strong>items, </strong>so function will be called again to calculate a new value when items state updates.</p><div><hr></div><h3><strong>Differences Between </strong><code>useMemo</code><strong> and </strong><code>useCallback</code></h3><p>Let's summarize the differences between the two hooks:</p><ul><li><p><strong>Purpose : useMemo</strong> caches the return value of a function whereas <strong>useCallback</strong> caches the function definition itself.</p></li><li><p><strong>When to use : useMemo</strong> is used when you have an expensive calculation you want to avoid on every render. <strong>useCallback</strong> is used to cache a function to avoid re-creating it on every re-render.</p></li><li><p><strong>Dependencies : useMemo</strong> makes sure that an expensive function should only be called for changed dependencies. <strong>useCallback</strong> re-creates function when the dependencies change.</p></li><li><p><strong>Common use case : useMemo </strong>hook<strong> </strong>cache results of expensive calculations or data processing. <strong>useCallback </strong>passing memoized functions to child components.</p></li></ul><div><hr></div><h3>Summary:</h3><ul><li><p><strong>useMemo</strong> memoizes the <strong>result</strong> of an expensive computation and only recomputes it when the <strong>dependencies</strong> change.</p></li><li><p><strong>useCallback </strong>memoizes the <strong>function definition</strong> and only recreates the function when the <strong>dependencies</strong> change.</p></li><li><p><strong>useMemo </strong>is useful for avoiding expensive recalculations on every render.</p></li><li><p><strong>useCallback </strong>is useful for avoiding recreating the function on every render.</p></li><li><p>You should only use <strong>useMemo</strong> and <strong>useCallback</strong> it for <strong>performance optimizations</strong> when you notice performance bottlenecks.</p></li></ul><div><hr></div><p>Thanks a lot, I hope this was helpful.</p><h2>&#128075; Let&#8217;s connect</h2><blockquote><p>You can find me on <strong><a href="https://www.linkedin.com/in/sanjay-mehta-475280176/">LinkedIn</a></strong>.</p><p><em>If you like my content don&#8217;t forget to subscribe and hit the like </em>&#10084;&#65039;<em> button at the bottom to help support me or share this with a friend. It keeps me motivated to share more content and help people to learn more. </em>&#128591;</p></blockquote><p></p><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://sanjayofficial.substack.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">Thanks for reading Tech Newsletter! Subscribe for free to receive new posts and support my work.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div>]]></content:encoded></item><item><title><![CDATA[How useState hook works under the hood.]]></title><description><![CDATA[React hooks are not magic, they are just Arrays.]]></description><link>https://sanjayofficial.substack.com/p/coming-soon</link><guid isPermaLink="false">https://sanjayofficial.substack.com/p/coming-soon</guid><dc:creator><![CDATA[Sanjay Mehta]]></dc:creator><pubDate>Thu, 14 Nov 2024 14:27:01 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!a9w9!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2931b62e-9333-4932-a015-4516f25826d2_1200x800.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!a9w9!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2931b62e-9333-4932-a015-4516f25826d2_1200x800.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!a9w9!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2931b62e-9333-4932-a015-4516f25826d2_1200x800.png 424w, https://substackcdn.com/image/fetch/$s_!a9w9!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2931b62e-9333-4932-a015-4516f25826d2_1200x800.png 848w, https://substackcdn.com/image/fetch/$s_!a9w9!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2931b62e-9333-4932-a015-4516f25826d2_1200x800.png 1272w, https://substackcdn.com/image/fetch/$s_!a9w9!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2931b62e-9333-4932-a015-4516f25826d2_1200x800.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!a9w9!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2931b62e-9333-4932-a015-4516f25826d2_1200x800.png" width="1200" height="800" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/2931b62e-9333-4932-a015-4516f25826d2_1200x800.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:800,&quot;width&quot;:1200,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:320260,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:null,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!a9w9!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2931b62e-9333-4932-a015-4516f25826d2_1200x800.png 424w, https://substackcdn.com/image/fetch/$s_!a9w9!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2931b62e-9333-4932-a015-4516f25826d2_1200x800.png 848w, https://substackcdn.com/image/fetch/$s_!a9w9!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2931b62e-9333-4932-a015-4516f25826d2_1200x800.png 1272w, https://substackcdn.com/image/fetch/$s_!a9w9!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2931b62e-9333-4932-a015-4516f25826d2_1200x800.png 1456w" sizes="100vw" fetchpriority="high"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg role="img" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><title></title><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><div><hr></div><blockquote><p><strong>Let&#8217;s first try to understand some basic concepts before going into the depth of hook.</strong></p></blockquote><h2><strong>Hooks in React</strong></h2><p><strong>In React, useState, as well as any other function starting with &#8220;use&#8221;, is called a Hook.</strong></p><p>There are some limitations, where we need to use hook in our component.</p><ol><li><p><strong>Hooks can only be called at the top level of your components or your custom hooks.</strong></p></li></ol><pre><code><code>function MyButton() {
    const [count, setCount] = useState(0);
    // ...</code></code></pre><ol start="2"><li><p><strong>Don&#8217;t call Hooks inside loops, conditions, nested functions or inside a map call.</strong></p></li></ol><pre><code><code>&lt;ul&gt;
    {items.map((item) =&gt; {
        // Doesn't work!
        const ref = useRef(null);
        return &lt;li ref={ref} /&gt;;
    })} 
&lt;/ul&gt;;</code></code></pre><blockquote><p>You should <strong>use</strong> React features at the top of your component similar to how you <strong>import</strong> modules at the top of your file.</p></blockquote><div><hr></div><h3>useState Hook</h3><h4>What is state in React and why do we need state in our component?</h4><p>Components often need to change what&#8217;s on the screen as a result of an interaction. Typing into the form should update the input field, clicking <strong>next</strong> on an image carousel should change which image is displayed, clicking <strong>buy</strong> should put a product in the shopping cart.</p><div class="pullquote"><p> Components need to <strong>remember</strong> things: the <strong>current input value</strong>, the <strong>current image</strong>, the <strong>shopping cart</strong>. In React, this kind of component-specific <strong>memory</strong> is called <strong>state</strong>.</p></div><p>To update a component with new data, two things need to happen:</p><p>1. <strong>Retain</strong>&nbsp;the data between renders.</p><p>2. <strong>Trigger</strong>&nbsp;React to render the component with new data (re-rendering).</p><p>The <strong>useState</strong> Hook provides those two things:</p><p>1. A&nbsp;<strong>state variable</strong>&nbsp;to retain the data between renders.</p><p>2. A&nbsp;<strong>state setter function</strong>&nbsp;to update the variable and trigger React to render the component again.</p><pre><code><code>const [index, setIndex] = useState(0);</code></code></pre><p>In this case, you want React to remember <strong>index</strong>.</p><p>The convention is to name this pair like <strong>const [something, setSomething]</strong>. You could name it anything you like, but conventions make things easier to understand across projects.</p><p>The only argument to <strong>useState</strong> is the <strong>initial value</strong> of your state variable. In this example, the <strong>index&#8217;s initial value</strong> is set to <strong>0</strong> with <strong>useState(0)</strong>.</p><h3>What happens when you update the state?</h3><p>Let&#8217;s take the same index example to understand.</p><p><strong>1. Your component renders the first time.</strong>&nbsp;Because you passed&nbsp;<strong>0</strong>&nbsp;to&nbsp;<strong>useState</strong>&nbsp;as the initial value for&nbsp;<strong>index</strong>, it will return&nbsp;<strong>[0, setIndex]</strong>. React remembers&nbsp;<strong>0</strong>&nbsp;is the latest state value.</p><p><strong>2. You update the state.</strong>&nbsp;When a user clicks the button, it calls&nbsp;<strong>setIndex(index + 1)</strong>.&nbsp;<strong>index</strong>&nbsp;is&nbsp;<strong>0</strong>, so it&#8217;s&nbsp;<strong>setIndex(1)</strong>. This tells React to remember&nbsp;<strong>index</strong>&nbsp;is&nbsp;<strong>1</strong>&nbsp;now and triggers another render.</p><p><strong>3. Your component&#8217;s second render.</strong>&nbsp;React still sees&nbsp;<strong>useState(0)</strong>, but because React&nbsp;<strong>remembers</strong>&nbsp;that you set&nbsp;<strong>index</strong>&nbsp;to&nbsp;<strong>1</strong>, it returns&nbsp;<strong>[1, setIndex]</strong>&nbsp;instead.</p><p>4. And so on!</p><div><hr></div><h3>Let&#8217;s dive into deeper concept of how useState works under the hood.</h3><p></p><h4><strong>How does React know which state to return?</strong>&nbsp;</h4><p>There is no <strong>identifier</strong> that is passed to <strong>useState</strong>, so how does it know which of the state variables to return?</p><p>Internally, React holds <strong>an array of state pairs</strong> for every component. It also maintains the <strong>current pair index</strong>, which is set to <strong>0</strong> before rendering. Each time you call <strong>useState</strong>, React gives you the <strong>next state pair and increments the index.</strong></p><p>Note - It&#8217;s just gives an idea of how react <strong>useState</strong> hook works internally, real implementation may differ. </p><h4>useState function</h4><pre><code><code>let componentHooks = [];
let currentHookIndex = 0;

function useState(initialState) {
    let pair = componentHooks[currentHookIndex];
    if (pair) {
        currentHookIndex++;
        return pair;
    }
    pair = [initialState, setState];
    function setState(nextState) {
        pair[0] = nextState;
        updateDOM();
    }    
    componentHooks[currentHookIndex] = pair;
    currentHookIndex++;
    return pair;
}</code></code></pre><h4>updateDom function</h4><pre><code><code>function updateDOM() {
    currentHookIndex = 0;
    let output = ArtistGallery();

    nextButton.onclick = output.onNextClick;
    header.textContent = output.header;
    image.src = output.imageSrc;
    image.alt = output.imageAlt;
}</code></code></pre><h4>ArtistGallery Component</h4><pre><code><code>function ArtistGallery() {
    const [index, setIndex] = useState(0);
    function handleNextClick() {
        setIndex(index + 1);
    }   
    let image = imageList[index];
    return {
        onNextClick: handleNextClick,
        header: `${image.name} by ${image.artist}`,
        counter: `${index + 1} of ${imageList.length}`,
        imageSrc: imageList.url,
        imageAlt: imageList.alt
    };
}</code></code></pre><h4>demo.js file</h4><pre><code><code>let nextButton = document.getElementById('nextButton');
let header = document.getElementById('header');
let image = document.getElementById('image');

let imageList = [{
    name: 'Homenaje a la Neurocirug&#237;a',
    artist: 'Marta Colvin Andrade',
    url: 'https://i.imgur.com/Mx7dA2Y.jpg',
    alt: 'A bronze statue of two crossed hands delicately holding a human brain in their fingertips.'
    },{
    name: 'Floralis Gen&#233;rica',
    artist: 'Eduardo Catalano',
    url: 'https://i.imgur.com/ZF6s192m.jpg',
    alt: 'A gigantic metallic flower sculpture with reflective mirror-like petals and strong stamens.'
    },{
    name: 'Eternal Presence',
    artist: 'John Woodrow Wilson',
    url: 'https://i.imgur.com/aTtVpES.jpg',
    alt: 'The sculpture depicting a human head seems ever-present and solemn. It radiates calm and serenity.'
    }];

updateDOM();</code></code></pre><h4>Let&#8217;s try to understand this code step by step.</h4><h4>useState function</h4><ol><li><p><strong>As component can use multiple hooks so, it creates an array of component hooks and the current hook index variable and set the initial value to 0.</strong></p></li></ol><pre><code><code>let componentHooks = [];
let currentHookIndex = 0;</code></code></pre><ol start="2"><li><p><strong>React checks if this is not the first render, it returns the existing state pair and prepare for the next hook call.</strong></p></li></ol><pre><code><code>let pair = componentHooks[currentHookIndex];
if (pair) {
    currentHookIndex++;
    return pair;
}</code></code></pre><ol start="3"><li><p><strong>If this is the first time we&#8217;re rendering react create a new state pair and store the pair for future renders and prepare for the next hook call.</strong></p></li></ol><pre><code><code>pair = [initialState, setState];
componentHooks[currentHookIndex] = pair;
currentHookIndex++;
return pair;</code></code></pre><p><strong>4.  Updating the state using set state function. When the user requests a state change, react put the new value into the pair.</strong></p><pre><code><code>function setState(nextState) { 
    pair[0] = nextState;
    updateDOM();
}</code></code></pre><ol start="5"><li><p><strong>When the user requests for state change, it also triggers the updateDOM() function. The updateDOM function resets the value of the currentHookIndex to 0  and assign the new values which is returned from the component.</strong></p></li></ol><pre><code><code>currentHookIndex = 0;
let output = ArtistGallery();
nextButton.onclick = output.onNextClick;
header.textContent = output.header;
image.src = output.imageSrc;
image.alt = output.imageAlt;</code></code></pre><h4>ArtistGallery Component</h4><p><strong>ArtistGallery component using the useState function and initializing the index value to 0. In this example we&#8217;re not using React so, this component returns object as the output instead of JSX.</strong></p><pre><code><code>return {     
    onNextClick: handleNextClick,
    header: `${image.name} by ${image.artist}`,
    counter: `${index + 1} of ${imageList.length}`,
    imageSrc: imageList.url,   
    imageAlt: imageList.alt
};</code></code></pre><h4>demo.js file</h4><p><strong>This file is created to make the UI match with the initial state by calling the updateDOM() function initially.</strong></p><pre><code><code>let nextButton = document.getElementById('nextButton');
let header = document.getElementById('header');
let image = document.getElementById('image');

let imageList = [{
    name: 'Homenaje a la Neurocirug&#237;a',
    artist: 'Marta Colvin Andrade',
    url: 'https://i.imgur.com/Mx7dA2Y.jpg',
    alt: 'A bronze statue of two crossed hands delicately holding a human brain in their fingertips.'
    },{
    name: 'Floralis Gen&#233;rica',
    artist: 'Eduardo Catalano',
    url: 'https://i.imgur.com/ZF6s192m.jpg',
    alt: 'A gigantic metallic flower sculpture with reflective mirror-like petals and strong stamens.'
    },{
    name: 'Eternal Presence',
    artist: 'John Woodrow Wilson',
    url: 'https://i.imgur.com/aTtVpES.jpg',
    alt: 'The sculpture depicting a human head seems ever-present and solemn. It radiates calm and serenity.'
    }];

updateDOM();</code></code></pre><div><hr></div><h4>Summary </h4><ul><li><p>If you want your component to remember some information between renders use <strong>state.</strong></p></li><li><p>Hooks are special functions that start with&nbsp;<strong>use</strong>.</p></li><li><p>The&nbsp;<strong>useState</strong>&nbsp;Hook returns a <strong>pair of values</strong>: the <strong>current state</strong> and the <strong>function to update it</strong>.</p></li><li><p>You can have <strong>more than one state variable</strong>. Internally, React matches them up by their order.</p></li></ul><p>Thanks a lot, I hope this was helpful.</p><h2>&#128075; Let&#8217;s connect</h2><blockquote><p>You can find me on <strong><a href="https://www.linkedin.com/in/sanjay-mehta-475280176/">LinkedIn</a></strong>.</p><p><em>If you like my content don&#8217;t forget to subscribe and hit the like </em>&#10084;&#65039;<em> button at the bottom to help support me or share this with a friend. It keeps me motivated to share more content and help people to learn more. </em>&#128591;</p></blockquote><p></p><p class="button-wrapper" data-attrs="{&quot;url&quot;:&quot;https://sanjayofficial.substack.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe now&quot;,&quot;action&quot;:null,&quot;class&quot;:null}" data-component-name="ButtonCreateButton"><a class="button primary" href="https://sanjayofficial.substack.com/subscribe?"><span>Subscribe now</span></a></p>]]></content:encoded></item><item><title><![CDATA[Principals of Reliable Applications]]></title><description><![CDATA[A reliable distributed system is composed of reliable applications.]]></description><link>https://sanjayofficial.substack.com/p/principals-of-reliable-applications-64970c07610e</link><guid isPermaLink="false">https://sanjayofficial.substack.com/p/principals-of-reliable-applications-64970c07610e</guid><dc:creator><![CDATA[Sanjay Mehta]]></dc:creator><pubDate>Fri, 12 Jan 2024 05:35:35 GMT</pubDate><enclosure url="https://substack-post-media.s3.amazonaws.com/public/images/dd86526a-b36a-46a2-a1b7-6b24bb04a642_800x618.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<div class="captioned-image-container"><figure><a class="image-link image2" target="_blank" href="https://substackcdn.com/image/fetch/$s_!om75!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F309d0d85-8d3d-4d3c-ab2a-ec728e5dfcea_800x618.jpeg" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!om75!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F309d0d85-8d3d-4d3c-ab2a-ec728e5dfcea_800x618.jpeg 424w, https://substackcdn.com/image/fetch/$s_!om75!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F309d0d85-8d3d-4d3c-ab2a-ec728e5dfcea_800x618.jpeg 848w, https://substackcdn.com/image/fetch/$s_!om75!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F309d0d85-8d3d-4d3c-ab2a-ec728e5dfcea_800x618.jpeg 1272w, https://substackcdn.com/image/fetch/$s_!om75!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F309d0d85-8d3d-4d3c-ab2a-ec728e5dfcea_800x618.jpeg 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!om75!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F309d0d85-8d3d-4d3c-ab2a-ec728e5dfcea_800x618.jpeg" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/309d0d85-8d3d-4d3c-ab2a-ec728e5dfcea_800x618.jpeg&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:null,&quot;width&quot;:null,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:null,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:null,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:null,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!om75!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F309d0d85-8d3d-4d3c-ab2a-ec728e5dfcea_800x618.jpeg 424w, https://substackcdn.com/image/fetch/$s_!om75!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F309d0d85-8d3d-4d3c-ab2a-ec728e5dfcea_800x618.jpeg 848w, https://substackcdn.com/image/fetch/$s_!om75!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F309d0d85-8d3d-4d3c-ab2a-ec728e5dfcea_800x618.jpeg 1272w, https://substackcdn.com/image/fetch/$s_!om75!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F309d0d85-8d3d-4d3c-ab2a-ec728e5dfcea_800x618.jpeg 1456w" sizes="100vw" fetchpriority="high"></picture><div></div></div></a></figure></div><blockquote><p>A reliable distributed system is composed of reliable applications.</p></blockquote><p>Reliable applications have several positive properties, and these properties help us when we&#8217;re building distributed systems, but they&#8217;re also good just on their own. Some of these properties are <strong>idempotence</strong>, <strong>immutability</strong>, <strong>location independence</strong>, and <strong>versioning</strong>.</p><h4><strong>Idempotence</strong></h4><blockquote><p>Idempotence is a property that helps us to tolerate unreliable networks.</p></blockquote><p>When the network is unreliable, the client might have to retry, and an idempotent application won&#8217;t duplicate the effect if it receives a duplicate message.</p><div class="captioned-image-container"><figure><a class="image-link image2" target="_blank" href="https://substackcdn.com/image/fetch/$s_!D9Wc!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F51ba10c8-bd2c-4447-b6bf-d705ed946d33_800x648.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!D9Wc!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F51ba10c8-bd2c-4447-b6bf-d705ed946d33_800x648.png 424w, https://substackcdn.com/image/fetch/$s_!D9Wc!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F51ba10c8-bd2c-4447-b6bf-d705ed946d33_800x648.png 848w, https://substackcdn.com/image/fetch/$s_!D9Wc!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F51ba10c8-bd2c-4447-b6bf-d705ed946d33_800x648.png 1272w, https://substackcdn.com/image/fetch/$s_!D9Wc!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F51ba10c8-bd2c-4447-b6bf-d705ed946d33_800x648.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!D9Wc!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F51ba10c8-bd2c-4447-b6bf-d705ed946d33_800x648.png" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/51ba10c8-bd2c-4447-b6bf-d705ed946d33_800x648.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:null,&quot;width&quot;:null,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:null,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:null,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:null,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!D9Wc!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F51ba10c8-bd2c-4447-b6bf-d705ed946d33_800x648.png 424w, https://substackcdn.com/image/fetch/$s_!D9Wc!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F51ba10c8-bd2c-4447-b6bf-d705ed946d33_800x648.png 848w, https://substackcdn.com/image/fetch/$s_!D9Wc!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F51ba10c8-bd2c-4447-b6bf-d705ed946d33_800x648.png 1272w, https://substackcdn.com/image/fetch/$s_!D9Wc!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F51ba10c8-bd2c-4447-b6bf-d705ed946d33_800x648.png 1456w" sizes="100vw"></picture><div></div></div></a></figure></div><p><strong>Problems with CRUD</strong></p><p><strong>CRUD</strong> stands for create, read, update, and delete. These are four operations that you can use in order to create and modify entities within your system. The default position for mapping these four operations onto a RESTful API is to map <strong>create</strong> to <strong>POST</strong>, <strong>read</strong> to <strong>GET</strong>, <strong>update</strong> to <strong>PUT</strong>, and <strong>delete</strong>, of course, to <strong>DELETE</strong>.</p><p>Now the problem with that default mapping has to do with idempotence. In REST, the PUT and DELETE verbs are specified to be <strong>idempotent</strong>, but POST is not <strong>idempotent</strong>. An <strong>idempotent</strong> operation is one that will have no effect if it is received a second time. So, for example, if you were to PUT some contents to a resource and then repeat that PUT, the second one wouldn&#8217;t change the contents. POST, however, is not guaranteed to be idempotent by default. That means if you were to POST to a resource twice, you would end up with two different entities.</p><p>Remember, the <strong>network</strong> is <strong>unreliable</strong>. Let&#8217;s see what happens with a typical API when the client has to retry. Let&#8217;s say that the client wants to create a new employee, and so they&#8217;re going to POST to the /employees resource. The first time the server is going to insert into the Employee table and then come up with the new unique ID of 37. This is an <strong>auto&#8209;incrementing ID</strong> that the database generates upon <strong>INSERT</strong>. The server then responds with a 201 Created and the URL /employees/37. But remember, the network is unreliable. So what if the client never hears about this 201? The client has no choice but to try again. Now whether that&#8217;s the user clicking submit twice or something within the application performing a retry, it doesn&#8217;t matter. The application is going to end up sending another <strong>POST</strong> to /employees. On that <strong>second</strong> <strong>POST</strong>, the server is also going to do an <strong>INSERT</strong> into the Employee table, but this time it&#8217;s going to come back with the ID of 38. So the second time we return a 201 CREATED /employees/38. This operation is not <strong>idempotent</strong> because upon the second receipt of the same message, the server duplicated the effect. It ends up inserted two rows.</p><p>In order to behave in an idempotent manner, it needs to determine whether the client intended to create a second employee or if that was just a duplicate message. But in this particular API, every creation looks exactly the same. And so the server can&#8217;t tell the difference between an intentional creation of a second object and a retry.</p><p><strong>The solution</strong> is to introduce a <strong>client&#8209;side ID</strong>. You see, if the client knows the ID of the object before it&#8217;s created, then the server can tell the difference between the creation of a new object and a duplicate message. Duplicate messages will carry the same IDs as the original. And now if the client is supposed to know the ID before creation, we can&#8217;t wait for the server to run an INSERT on the database in order to generate the ID. And so we have to use a different ID than the auto incrementing key in the database. In this case, we chooses to use a GUID as the ID of a employee. we&#8217;ll represent this as an alternate key in the database. And then, we&#8217;ll redesign the API to look like this. To create a new employee, the client will POST to /employees/abc&#8209;123, the GUID of the employee that they intend to create. Upon first receipt of this message, the server will see that that alternate key does not exist within the Employee table. It will therefore insert the row and then return a 201 CREATED /employees/abc&#8209;123. The table still has a primary key, which is an auto&#8209;incrementing ID, but that ID is never returned through the API. But let&#8217;s suppose that our unreliable network has dropped that 201 response message, and so the client retries. The client still has the ID that it intends to create, and so it sends a POST to /employees/abc&#8209;123. This time when the server sees that message, it can tell that that alternate key already exists within the Employee table. It therefore does not insert an additional row, but it still returns 201 CREATED /employees/abc&#8209;123. And so with these two changes to the API design and to the database design, we will be able to implement <strong>idempotence</strong> on the server side.</p><h4>Immutability</h4><blockquote><p>Immutability is good because that means that we keep a record of everything that happened within the system. And a beautiful application won&#8217;t destroy data by overwriting it or deleting it.</p></blockquote><div class="captioned-image-container"><figure><a class="image-link image2" target="_blank" href="https://substackcdn.com/image/fetch/$s_!rB1X!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F61c383bd-5067-4306-8a08-ee5dbb034b4f_800x395.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!rB1X!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F61c383bd-5067-4306-8a08-ee5dbb034b4f_800x395.png 424w, https://substackcdn.com/image/fetch/$s_!rB1X!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F61c383bd-5067-4306-8a08-ee5dbb034b4f_800x395.png 848w, https://substackcdn.com/image/fetch/$s_!rB1X!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F61c383bd-5067-4306-8a08-ee5dbb034b4f_800x395.png 1272w, https://substackcdn.com/image/fetch/$s_!rB1X!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F61c383bd-5067-4306-8a08-ee5dbb034b4f_800x395.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!rB1X!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F61c383bd-5067-4306-8a08-ee5dbb034b4f_800x395.png" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/61c383bd-5067-4306-8a08-ee5dbb034b4f_800x395.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:null,&quot;width&quot;:null,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:null,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:null,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:null,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!rB1X!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F61c383bd-5067-4306-8a08-ee5dbb034b4f_800x395.png 424w, https://substackcdn.com/image/fetch/$s_!rB1X!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F61c383bd-5067-4306-8a08-ee5dbb034b4f_800x395.png 848w, https://substackcdn.com/image/fetch/$s_!rB1X!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F61c383bd-5067-4306-8a08-ee5dbb034b4f_800x395.png 1272w, https://substackcdn.com/image/fetch/$s_!rB1X!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F61c383bd-5067-4306-8a08-ee5dbb034b4f_800x395.png 1456w" sizes="100vw" loading="lazy"></picture><div></div></div></a></figure></div><p><strong>Immutability</strong> as a default has several different advantages, some technical and some business advantages. One business advantage is that immutability gives you a reliable <strong>audit log</strong>. If you can&#8217;t change or delete the information that&#8217;s in the database, then every decision becomes an insert. Every row is an entry in your audit log, capturing the intent of the user. Another advantage on both the business and the technical side is that immutable systems do not destroy data. Immutable records cannot be deleted, and they cannot be updated where updates would replace or destroy the information that used to be in that record. But the most important technical advantage of immutability is that it preserves metadata. Preserving metadata is especially important in a distributed system. <strong>Metadata</strong> reveals which information a certain node has received in the past and therefore can control how it reacts to new information in the future. Metadata allows remote peers to converge and become eventually consistent.</p><p><strong>Immutability</strong> is a great default for distributed systems. we will choose two very simple patterns to begin with. The first one is <strong>snapshots</strong>. Rather than keeping the mutable state of an employees within the Employee table, we are going to keep a separate snapshot table, and this will be called Employee Description table. Every time a user wants to change the description of a <strong>employee</strong>, they will end up inserting a row into the <strong>snapshot</strong> table. That will simulate <strong>updates</strong>, but what about <strong>deletes</strong>? Well for that, we will use the <strong>tombstone</strong> pattern. Instead of actually deleting the employee record, we&#8217;ll insert a new record into the Employee Removed table. The presence of this employee removed child record indicates that the employee has been deleted. Both Employee Description and Employee Removed table have a employeeID foreign key, and they also contain a date. All tables in this system have an alternate key, and these two are no exception. The alternate keys of these two tables are the EmployeeID and either the date modified or the date removed.</p><h4>Location Independence</h4><blockquote><p>Distributed systems are made up of different applications that are deployed to different locations. If the behavior of an application is dependent upon where it&#8217;s deployed, its location, then that causes problems while composing it into a distributed system.</p></blockquote><div class="captioned-image-container"><figure><a class="image-link image2" target="_blank" href="https://substackcdn.com/image/fetch/$s_!VA9I!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4d07fd4e-d18e-4bbe-a943-bf0ea400c126_662x441.jpeg" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!VA9I!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4d07fd4e-d18e-4bbe-a943-bf0ea400c126_662x441.jpeg 424w, https://substackcdn.com/image/fetch/$s_!VA9I!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4d07fd4e-d18e-4bbe-a943-bf0ea400c126_662x441.jpeg 848w, https://substackcdn.com/image/fetch/$s_!VA9I!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4d07fd4e-d18e-4bbe-a943-bf0ea400c126_662x441.jpeg 1272w, https://substackcdn.com/image/fetch/$s_!VA9I!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4d07fd4e-d18e-4bbe-a943-bf0ea400c126_662x441.jpeg 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!VA9I!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4d07fd4e-d18e-4bbe-a943-bf0ea400c126_662x441.jpeg" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/4d07fd4e-d18e-4bbe-a943-bf0ea400c126_662x441.jpeg&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:null,&quot;width&quot;:null,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:null,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:null,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:null,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!VA9I!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4d07fd4e-d18e-4bbe-a943-bf0ea400c126_662x441.jpeg 424w, https://substackcdn.com/image/fetch/$s_!VA9I!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4d07fd4e-d18e-4bbe-a943-bf0ea400c126_662x441.jpeg 848w, https://substackcdn.com/image/fetch/$s_!VA9I!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4d07fd4e-d18e-4bbe-a943-bf0ea400c126_662x441.jpeg 1272w, https://substackcdn.com/image/fetch/$s_!VA9I!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4d07fd4e-d18e-4bbe-a943-bf0ea400c126_662x441.jpeg 1456w" sizes="100vw" loading="lazy"></picture><div></div></div></a></figure></div><p>The <strong>third</strong> property that we want in a <strong>reliable application</strong> is <strong>location</strong> <strong>independence</strong>. <strong>Location independence</strong> implies that an application&#8217;s behavior does not depend upon its location. In other words, if you were to deploy an application to multiple locations and then send the same message to each instance, they would all produce the same behavior. This might seem like a property that we get almost for free, but we&#8217;ve already seen one example of an application design pattern that is not location independent, and that is the use of <strong>auto&#8209;incrementing IDs</strong>. An <strong>auto&#8209;incrementing ID</strong> generated on one database is only good at that one database. As an identifier for a row, it&#8217;s dependent upon that location. If we were to insert the same object into databases at different locations, they would each come up with different identifiers. Where still, databases in different locations will come up with the same identifier for different objects.</p><p>The solution to the above problem is to use <strong>hash</strong>, which is <strong>great location independent identifier</strong>. When hashes are used as identifiers, the pattern is known as <strong>content&#8209;addressed storage</strong>. <strong>Content&#8209;address storage</strong> means that you&#8217;re using the content to identify itself. It works by computing the hash of the content that you want to store and then storing that in a location addressed by that hash. Now if somebody wants to refer to that object, they simply reference it by its hash. Unlike an auto&#8209;incremented ID, content&#8209;addressed storage is location independent. Every single instance of the application will compute the same hash for a given object. The hash depends only upon the content and not upon anything else that might happen to be stored at that location. Furthermore, different locations storing different objects are very unlikely to produce the same hash. Hash collisions are vanishingly rare.</p><p>Now, if you&#8217;re thinking, that&#8217;s a really strange way to identify an object, well, you&#8217;re probably already familiar with an existing implementation of content&#8209;addressed storage. <strong>Docker</strong>, for example, uses content&#8209;addressed storage in order to identify images. The identity of a Docker image is the hash of the steps that it took to produce it. You might also be familiar with <strong>Git</strong>. Git uses the SHA&#8209;1 hash of the commit as its identity.</p><h4>Versioning</h4><blockquote><p>Things change over time, and a well&#8209;versioned application will tolerate those changes over time.</p></blockquote><div class="captioned-image-container"><figure><a class="image-link image2" target="_blank" href="https://substackcdn.com/image/fetch/$s_!Ar9i!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff6683dc0-d3a4-4827-83cc-128f0a35a243_700x394.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!Ar9i!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff6683dc0-d3a4-4827-83cc-128f0a35a243_700x394.png 424w, https://substackcdn.com/image/fetch/$s_!Ar9i!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff6683dc0-d3a4-4827-83cc-128f0a35a243_700x394.png 848w, https://substackcdn.com/image/fetch/$s_!Ar9i!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff6683dc0-d3a4-4827-83cc-128f0a35a243_700x394.png 1272w, https://substackcdn.com/image/fetch/$s_!Ar9i!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff6683dc0-d3a4-4827-83cc-128f0a35a243_700x394.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!Ar9i!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff6683dc0-d3a4-4827-83cc-128f0a35a243_700x394.png" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/f6683dc0-d3a4-4827-83cc-128f0a35a243_700x394.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:null,&quot;width&quot;:null,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:null,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:null,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:null,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!Ar9i!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff6683dc0-d3a4-4827-83cc-128f0a35a243_700x394.png 424w, https://substackcdn.com/image/fetch/$s_!Ar9i!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff6683dc0-d3a4-4827-83cc-128f0a35a243_700x394.png 848w, https://substackcdn.com/image/fetch/$s_!Ar9i!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff6683dc0-d3a4-4827-83cc-128f0a35a243_700x394.png 1272w, https://substackcdn.com/image/fetch/$s_!Ar9i!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff6683dc0-d3a4-4827-83cc-128f0a35a243_700x394.png 1456w" sizes="100vw" loading="lazy"></picture><div></div></div></a></figure></div><p>The final property that we wants to ensure that our reliable application has is proper <strong>versioning</strong>. we know that the <strong>network</strong> is not <strong>homogenous</strong>, and that means that different versions or applications are going to be deployed across different locations at different times. As this happens, we wants to make sure that we maintains the contract across those changes, and so we are going to want to make sure that we puts a good versioning strategy in place from the beginning.</p><p>To consider how to version an application, we are going to break it down into <strong>three</strong> large components. <strong>An application consists of code, data, and an API</strong>. The <strong>code</strong> is by far the easiest of these three to version. We can use tools like source control and continuous integration and continuous delivery pipelines in order to make sure that we&#8217;re delivering a consistent set of application code. And when the code is downloaded in pieces to the browser, we can use content&#8209;addressed storage in order to make sure that all of the artifacts are consistent with one another. While code versioning is easy, data versioning is a little bit more tricky. <strong>Data</strong> will be stored on each of the different nodes, and we&#8217;ll have to migrate that data to the next version in order to evolve the application. Since we are going to favor creating new tables, rather than adding columns to existing tables and finally, while data might be tricky, <strong>API versioning</strong> is downright difficult. Here, we consider the API of an application to be the endpoints that you can call, as well as the messages that you send and receive. API management is really application lifecycle management, because application interfaces evolve over time. There is no agreed&#8209;upon best practice for evolving an API.</p><p>We can use the <strong>URL strategy</strong> in order to indicate the version of the API. As the API evolves, the path changes to include a new version number. Another strategy would be to use <strong>content types</strong> in order to version APIs. A client would use an application&#8209;defined Accept header, and the server supply an application&#8209;defined Content&#8209;Type. While this is more in keeping with the design philosophy of REST, it&#8217;s a bit more difficult to implement. And <strong>the final versioning strategy is to simply avoid versioning</strong>, and while this might at first seem like an irresponsible strategy, it&#8217;s precisely the strategy that <strong>GraphQL</strong> uses. <strong>GraphQL</strong> favors version-less APIs and allows the client to choose what the structure of their response.</p><h4>Summary</h4><p>These <strong>four properties</strong> are not the default. They don&#8217;t come with any application template. It requires a bit more effort and buy&#8209;in from application development teams, but the results are well worth it. By having these practices in place ahead of time, we know that each of the applications that our team builds are going to be <strong>good citizens of a distributed system</strong>. If you don&#8217;t need to build distributed systems, then stop right here. Apply these principles, and your applications will be more reliable.</p>]]></content:encoded></item><item><title><![CDATA[Things to know about Java Collection]]></title><description><![CDATA[1. ArrayList subList() method]]></description><link>https://sanjayofficial.substack.com/p/things-to-know-about-java-collection-d5091a15aa07</link><guid isPermaLink="false">https://sanjayofficial.substack.com/p/things-to-know-about-java-collection-d5091a15aa07</guid><dc:creator><![CDATA[Sanjay Mehta]]></dc:creator><pubDate>Sat, 11 Dec 2021 16:03:30 GMT</pubDate><enclosure url="https://substack-post-media.s3.amazonaws.com/public/images/09956886-b52e-4826-80bd-31c9ec9f0c44_800x600.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<div class="captioned-image-container"><figure><a class="image-link image2" target="_blank" href="https://substackcdn.com/image/fetch/$s_!fNiG!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fbd22583e-b4f2-456a-b8f5-d5eb443e6b0c_800x600.jpeg" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!fNiG!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fbd22583e-b4f2-456a-b8f5-d5eb443e6b0c_800x600.jpeg 424w, https://substackcdn.com/image/fetch/$s_!fNiG!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fbd22583e-b4f2-456a-b8f5-d5eb443e6b0c_800x600.jpeg 848w, https://substackcdn.com/image/fetch/$s_!fNiG!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fbd22583e-b4f2-456a-b8f5-d5eb443e6b0c_800x600.jpeg 1272w, https://substackcdn.com/image/fetch/$s_!fNiG!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fbd22583e-b4f2-456a-b8f5-d5eb443e6b0c_800x600.jpeg 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!fNiG!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fbd22583e-b4f2-456a-b8f5-d5eb443e6b0c_800x600.jpeg" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/bd22583e-b4f2-456a-b8f5-d5eb443e6b0c_800x600.jpeg&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:null,&quot;width&quot;:null,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:null,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:null,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:null,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!fNiG!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fbd22583e-b4f2-456a-b8f5-d5eb443e6b0c_800x600.jpeg 424w, https://substackcdn.com/image/fetch/$s_!fNiG!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fbd22583e-b4f2-456a-b8f5-d5eb443e6b0c_800x600.jpeg 848w, https://substackcdn.com/image/fetch/$s_!fNiG!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fbd22583e-b4f2-456a-b8f5-d5eb443e6b0c_800x600.jpeg 1272w, https://substackcdn.com/image/fetch/$s_!fNiG!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fbd22583e-b4f2-456a-b8f5-d5eb443e6b0c_800x600.jpeg 1456w" sizes="100vw" fetchpriority="high"></picture><div></div></div></a></figure></div><h3>1. ArrayList subList() method</h3><p>As many of us know the <strong>subList()</strong> method of <strong>java.util.ArrayList</strong> class is used to return the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive. (If fromIndex and toIndex are equal, the returned list is empty.)</p><p>But, it not only returns the portion of the list, but it also returns a view of the portion of the list. Let&#8217;s understand better with the help of code!</p><pre><code>List&lt;String&gt; namesList = new ArrayList&lt;&gt;();</code></pre><pre><code>namesList.add("David");
namesList.add("George");
namesList.add("Anne");
namesList.add("Bailey");
namesList.add("Carol");</code></pre><pre><code>System.out.println("Original State of namesList : "+namesList);</code></pre><pre><code># Output of original List
Original State of namesList : [David, George, Anne, Bailey, Carol]</code></pre><pre><code># Get a view of list from index 1 to 3
List&lt;String&gt; subList = namesList.subList(1, 4);</code></pre><pre><code># Sort the elements in reverse order
subList.sort(Comparator.reverseOrder());</code></pre><pre><code>System.out.println("Original State of namesList after sorting subList : "+namesList);</code></pre><pre><code># Output of original List
Original State of namesList after sorting subList : [David, George, Bailey, Anne, Carol]</code></pre><p>The returned list is backed by the original list, so non-structural changes in the returned list are reflected in the original list, and vice-versa. The returned list supports all of the optional list operations.</p><p>So, if you try to make any structural changes in the returned list by using methods like add and clear. you will get <strong>UnsupportedOperationException</strong>.</p><h3>2. Arrays asList()&nbsp;method</h3><p>The List returned using Arrays.asList() method is a <strong>fixed-size </strong><em><strong>List</strong></em>, we can&#8217;t <strong>add/remove elements</strong>.</p><pre><code>String[] flowers = { "Ageratum", "Allium", "Poppy", "Catmint" };  List&lt;String&gt; flowerList = Arrays.asList(flowers);  </code></pre><pre><code>flowerList.add("Celosia"); // throws UnsupportedOperationException</code></pre><p>The root of this <em><strong>Exception</strong></em> is that the returned object doesn&#8217;t implement the <em>add() </em>operation since it isn&#8217;t the same as <em>java.util.ArrayList.</em></p><p>There are ways by which we can get the mutable list from <strong>Arrays.asList</strong> method.</p><p>For instance, we can pass the return object of <strong>Arrays.asList</strong> method in the constructor of <strong>ArrayList</strong>, which will support the add and remove operations.</p><pre><code>String[] flowers = { "Ageratum", "Allium", "Poppy", "Catmint" };  List&lt;String&gt; flowerList = new ArrayList&lt;&gt;(Arrays.asList(flowers));</code></pre><h3><strong>3. Double Brace Initialization</strong></h3><p>Double braces can be used for <strong>creating and initializing objects in a single Java expression</strong>.</p><h4>Standard Approach:</h4><p>Normally we initialize and populate a set as follows:</p><pre><code>Set&lt;String&gt; countries = new HashSet&lt;String&gt;();                     countries.add("India");     
countries.add("USA");
countries.add("USSR");</code></pre><p>As you can see in the above code</p><ol><li><p>Create an instance of <em>HashSet</em></p></li><li><p>Add countries to the <em>HashSet</em></p></li></ol><h4><strong>Using Double&nbsp;Brace:</strong></h4><p>We can actually combine the creation and initialization in a single statement; this is where we make use of double braces:</p><pre><code>Set&lt;String&gt; countries = new HashSet&lt;String&gt;() {{ 
           
add("India");            
add("USSR");            
add("USA");        
       
}};</code></pre><p>As you can see in the above code:</p><ol><li><p>Creating an anonymous inner class that extends <em>HashSet</em></p></li><li><p>Providing an instance initialization block that invokes the add method and adds the country name to the <em>HashSet</em></p></li></ol><h4>Advantages of using Double&nbsp;Brace:</h4><ul><li><p>Fewer lines of code compared to the native way of creation and initialization.</p></li><li><p>The code is more readable.</p></li><li><p>Creation initialization is done in the same expression.</p></li></ul><p>Thank you, for reading this post, hope you liked it please give applause.</p>]]></content:encoded></item><item><title><![CDATA[It’s all about RxJS Subject]]></title><description><![CDATA[A Subject is like an Observable, but can multicast to many Observers. Subjects are like EventEmitters: they maintain a registry of many&#8230;]]></description><link>https://sanjayofficial.substack.com/p/its-all-about-rxjs-subject-f749e09b73ae</link><guid isPermaLink="false">https://sanjayofficial.substack.com/p/its-all-about-rxjs-subject-f749e09b73ae</guid><dc:creator><![CDATA[Sanjay Mehta]]></dc:creator><pubDate>Sat, 18 Sep 2021 09:45:26 GMT</pubDate><enclosure url="https://substack-post-media.s3.amazonaws.com/public/images/c4b6a8fe-1fe2-49bd-a1c5-184c1a3ae65c_800x533.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<blockquote><p>A Subject is like an Observable, but can multicast to many Observers. Subjects are like EventEmitters: they maintain a registry of many listeners.</p></blockquote><div class="captioned-image-container"><figure><a class="image-link image2" target="_blank" href="https://substackcdn.com/image/fetch/$s_!ciLW!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc3a78a86-0651-4ffd-8d8b-3f3160706b5f_800x533.jpeg" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!ciLW!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc3a78a86-0651-4ffd-8d8b-3f3160706b5f_800x533.jpeg 424w, https://substackcdn.com/image/fetch/$s_!ciLW!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc3a78a86-0651-4ffd-8d8b-3f3160706b5f_800x533.jpeg 848w, https://substackcdn.com/image/fetch/$s_!ciLW!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc3a78a86-0651-4ffd-8d8b-3f3160706b5f_800x533.jpeg 1272w, https://substackcdn.com/image/fetch/$s_!ciLW!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc3a78a86-0651-4ffd-8d8b-3f3160706b5f_800x533.jpeg 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!ciLW!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc3a78a86-0651-4ffd-8d8b-3f3160706b5f_800x533.jpeg" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/c3a78a86-0651-4ffd-8d8b-3f3160706b5f_800x533.jpeg&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:null,&quot;width&quot;:null,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:null,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:null,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:null,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!ciLW!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc3a78a86-0651-4ffd-8d8b-3f3160706b5f_800x533.jpeg 424w, https://substackcdn.com/image/fetch/$s_!ciLW!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc3a78a86-0651-4ffd-8d8b-3f3160706b5f_800x533.jpeg 848w, https://substackcdn.com/image/fetch/$s_!ciLW!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc3a78a86-0651-4ffd-8d8b-3f3160706b5f_800x533.jpeg 1272w, https://substackcdn.com/image/fetch/$s_!ciLW!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc3a78a86-0651-4ffd-8d8b-3f3160706b5f_800x533.jpeg 1456w" sizes="100vw" fetchpriority="high"></picture><div></div></div></a></figure></div><p><strong>Every Subject is an Observable</strong>. You can subscribe to a Subject, providing an Observer, which will start receiving values normally. From the perspective of the Observer, it cannot tell whether the Observable execution is coming from a plain unicast Observable or a Subject.</p><p><strong>Every Subject is an Observer</strong>. It is an object with the methods <strong>next(v)</strong>, <strong>error(e)</strong>, and <strong>complete()</strong>. To feed a new value to the Subject, just call <strong>next(value),</strong> and it will be multicasted to the Observers registered to listen to the Subject.</p><p>Let&#8217;s see the example below for a better understanding:</p><pre><code>import { Subject } from 'rxjs';</code></pre><pre><code>const subject = new Subject&lt;number&gt;();</code></pre><pre><code>subject.subscribe({
  next: (v) =&gt; console.log(`observerA: ${v}`)
});
subject.subscribe({
  next: (v) =&gt; console.log(`observerB: ${v}`)
});</code></pre><pre><code>subject.next(1);
subject.next(2);</code></pre><pre><code>// Logs:
// observerA: 1
// observerB: 1
// observerA: 2
// observerB: 2</code></pre><p>Since a Subject is an Observer, this also means you may provide a Subject as the argument to the <strong>subscribe</strong> of any Observable.</p><pre><code>import { Subject, from } from 'rxjs';</code></pre><pre><code>const subject = new Subject&lt;number&gt;();</code></pre><pre><code>subject.subscribe({
  next: (v) =&gt; console.log(`observerA: ${v}`)
});
subject.subscribe({
  next: (v) =&gt; console.log(`observerB: ${v}`)
});</code></pre><pre><code>const observable = from([1, 2, 3]);</code></pre><pre><code>observable.subscribe(subject); // You can subscribe providing a Subject</code></pre><pre><code>// Logs:
// observerA: 1
// observerB: 1
// observerA: 2
// observerB: 2
// observerA: 3
// observerB: 3</code></pre><h3><strong>Few Specializations of the Subject&nbsp;type</strong></h3><ol><li><p><strong>BehaviorSubject</strong></p></li><li><p><strong>ReplaySubject</strong></p></li><li><p><strong>AsyncSubject</strong></p></li></ol><h3><strong>BehaviorSubject</strong></h3><p><em><strong>BehaviorSubject</strong>, which has a notion of "<strong>the current value</strong>". It stores the latest value emitted to its consumers, and whenever a new Observer subscribes, it will immediately receive the "current value" from the BehaviorSubject.</em></p><p>In the below example, the <strong>BehaviorSubject</strong> is initialized with the value <code>0</code> which the first Observer receives when it subscribes. The second Observer receives the value <code>2</code> even though it subscribed after the value <code>2</code> was sent.</p><pre><code>import { BehaviorSubject } from 'rxjs';
const subject = new BehaviorSubject(0); // 0 is the initial value</code></pre><pre><code>subject.subscribe({
  next: (v) =&gt; console.log(`observerA: ${v}`)
});</code></pre><pre><code>subject.next(1);
subject.next(2);</code></pre><pre><code>subject.subscribe({
  next: (v) =&gt; console.log(`observerB: ${v}`)
});</code></pre><pre><code>subject.next(3);</code></pre><pre><code>// Logs
// observerA: 0
// observerA: 1
// observerA: 2
// observerB: 2
// observerA: 3
// observerB: 3</code></pre><h3><strong>ReplaySubject</strong></h3><p><em>A </em><strong>ReplaySubject</strong><em> records multiple values from the Observable execution and replays them to new subscribers.</em></p><p>When creating a <strong>ReplaySubject</strong>, you can specify how many values to replay:</p><pre><code>import { ReplaySubject } from 'rxjs';
const subject = new ReplaySubject(3); // buffer 3 values for new subscribers</code></pre><pre><code>subject.subscribe({
  next: (v) =&gt; console.log(`observerA: ${v}`)
});</code></pre><pre><code>subject.next(1);
subject.next(2);
subject.next(3);
subject.next(4);</code></pre><pre><code>subject.subscribe({
  next: (v) =&gt; console.log(`observerB: ${v}`)
});</code></pre><pre><code>subject.next(5);</code></pre><pre><code>// Logs:
// observerA: 1
// observerA: 2
// observerA: 3
// observerA: 4
// observerB: 2
// observerB: 3
// observerB: 4
// observerA: 5
// observerB: 5</code></pre><p>As you can see last 3 values are stored for the new subscriber which is 2, 3, and 4.</p><p><strong>Window time in ReplaySubject</strong></p><p>ReplaySubject takes one more argument which specifies a <em>window time</em> in milliseconds.</p><p>Besides the buffer size, to determine how old the recorded values can be we can specify <em>window time.</em></p><p>Let&#8217;s see the example below, we use a large buffer size of <strong>100</strong>, but a window time parameter of just <strong>500</strong> milliseconds.</p><pre><code>import { ReplaySubject } from 'rxjs';
const subject = new ReplaySubject(100, 500 /* windowTime */);</code></pre><pre><code>subject.subscribe({
  next: (v) =&gt; console.log(`observerA: ${v}`)
});</code></pre><pre><code>let i = 1;
setInterval(() =&gt; subject.next(i++), 200);</code></pre><pre><code>setTimeout(() =&gt; {
  subject.subscribe({
    next: (v) =&gt; console.log(`observerB: ${v}`)
  });
}, 1000);</code></pre><pre><code>// Logs
// observerA: 1
// observerA: 2
// observerA: 3
// observerA: 4
// observerA: 5
// observerB: 3
// observerB: 4
// observerB: 5
// observerA: 6
// observerB: 6
// ...</code></pre><p>With the 500 milliseconds(0.5 second) windowTime the replay subject is only able to store the last 3 values under this time regardless of the buffer size.</p><h3><strong>AsyncSubject</strong></h3><p><em>The </em><strong>AsyncSubject</strong><em> is a variant where only the last value of the Observable execution is sent to its observers, and only when the execution completes.</em></p><pre><code>import { AsyncSubject } from 'rxjs';
const subject = new AsyncSubject();</code></pre><pre><code>subject.subscribe({
  next: (v) =&gt; console.log(`observerA: ${v}`)
});</code></pre><pre><code>subject.next(1);
subject.next(2);
subject.next(3);
subject.next(4);</code></pre><pre><code>subject.subscribe({
  next: (v) =&gt; console.log(`observerB: ${v}`)
});</code></pre><pre><code>subject.next(5);
subject.complete();</code></pre><pre><code>// Logs:
// observerA: 5
// observerB: 5</code></pre><p>In the above example, the last value observers will get only after calling <strong>subject.complete()</strong> without calling <strong>complete()</strong> method no value will be sent to observers.</p><p>Thank you, for reading this blog, hope you liked it please give applause and follow.</p>]]></content:encoded></item><item><title><![CDATA[First Step towards Git and Github]]></title><description><![CDATA[Introduction]]></description><link>https://sanjayofficial.substack.com/p/first-step-towards-git-and-github-bcb5107362e9</link><guid isPermaLink="false">https://sanjayofficial.substack.com/p/first-step-towards-git-and-github-bcb5107362e9</guid><dc:creator><![CDATA[Sanjay Mehta]]></dc:creator><pubDate>Fri, 10 Sep 2021 13:05:52 GMT</pubDate><enclosure url="https://substack-post-media.s3.amazonaws.com/public/images/a1c65b4b-a5c9-4907-b240-060285cea4e9_600x381.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<div class="captioned-image-container"><figure><a class="image-link image2" target="_blank" href="https://substackcdn.com/image/fetch/$s_!tid3!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3c0bb82b-8143-4d3e-a947-1e488e8c4fd1_600x381.jpeg" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!tid3!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3c0bb82b-8143-4d3e-a947-1e488e8c4fd1_600x381.jpeg 424w, https://substackcdn.com/image/fetch/$s_!tid3!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3c0bb82b-8143-4d3e-a947-1e488e8c4fd1_600x381.jpeg 848w, https://substackcdn.com/image/fetch/$s_!tid3!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3c0bb82b-8143-4d3e-a947-1e488e8c4fd1_600x381.jpeg 1272w, https://substackcdn.com/image/fetch/$s_!tid3!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3c0bb82b-8143-4d3e-a947-1e488e8c4fd1_600x381.jpeg 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!tid3!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3c0bb82b-8143-4d3e-a947-1e488e8c4fd1_600x381.jpeg" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/3c0bb82b-8143-4d3e-a947-1e488e8c4fd1_600x381.jpeg&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:null,&quot;width&quot;:null,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:null,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:null,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:null,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!tid3!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3c0bb82b-8143-4d3e-a947-1e488e8c4fd1_600x381.jpeg 424w, https://substackcdn.com/image/fetch/$s_!tid3!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3c0bb82b-8143-4d3e-a947-1e488e8c4fd1_600x381.jpeg 848w, https://substackcdn.com/image/fetch/$s_!tid3!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3c0bb82b-8143-4d3e-a947-1e488e8c4fd1_600x381.jpeg 1272w, https://substackcdn.com/image/fetch/$s_!tid3!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3c0bb82b-8143-4d3e-a947-1e488e8c4fd1_600x381.jpeg 1456w" sizes="100vw" fetchpriority="high"></picture><div></div></div></a></figure></div><h3>Introduction</h3><p>In the simple term&nbsp;, <strong>Git</strong><em> is software you install on your computer to interact with Git repositories and </em><strong>GitHub</strong><em> is a very popular website (and free to use), which is used to host GitHub repositories.</em></p><p><strong>Git</strong><em> </em>is a free and open-source <strong>distributed version control system</strong> designed to handle everything from small to very large projects with speed and efficiency.</p><p>Let&#8217;s understand what is <strong>Version Control System</strong>.</p><p><strong>Version control</strong> <em>is a system that records changes to a file or set of files over time so that you can recall specific versions later</em>.</p><div class="captioned-image-container"><figure><a class="image-link image2" target="_blank" href="https://substackcdn.com/image/fetch/$s_!LhgP!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8550bc89-f394-4744-ae0b-15f4db8b2e43_800x534.jpeg" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!LhgP!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8550bc89-f394-4744-ae0b-15f4db8b2e43_800x534.jpeg 424w, https://substackcdn.com/image/fetch/$s_!LhgP!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8550bc89-f394-4744-ae0b-15f4db8b2e43_800x534.jpeg 848w, https://substackcdn.com/image/fetch/$s_!LhgP!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8550bc89-f394-4744-ae0b-15f4db8b2e43_800x534.jpeg 1272w, https://substackcdn.com/image/fetch/$s_!LhgP!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8550bc89-f394-4744-ae0b-15f4db8b2e43_800x534.jpeg 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!LhgP!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8550bc89-f394-4744-ae0b-15f4db8b2e43_800x534.jpeg" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/8550bc89-f394-4744-ae0b-15f4db8b2e43_800x534.jpeg&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:null,&quot;width&quot;:null,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:null,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:null,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:null,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!LhgP!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8550bc89-f394-4744-ae0b-15f4db8b2e43_800x534.jpeg 424w, https://substackcdn.com/image/fetch/$s_!LhgP!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8550bc89-f394-4744-ae0b-15f4db8b2e43_800x534.jpeg 848w, https://substackcdn.com/image/fetch/$s_!LhgP!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8550bc89-f394-4744-ae0b-15f4db8b2e43_800x534.jpeg 1272w, https://substackcdn.com/image/fetch/$s_!LhgP!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8550bc89-f394-4744-ae0b-15f4db8b2e43_800x534.jpeg 1456w" sizes="100vw"></picture><div></div></div></a></figure></div><p><strong>Daily life example:</strong> <em>Imagine that your boss gave you a task to write an article on the paper in one hour. You are sure that you will finish perfectly but as we&nbsp;,are human there are always possibilities, to make mistakes. After one hour, you just realized that made a mistake. Oh, no! Was there a way to fix it?</em></p><p><em>In real life, you can take precautions on time to avoid unwanted situations or if something has really happened before prevention, simply means that it happened. So, we cannot change things occurred in past in actual life. Fortunately, version control systems help us to go back in time without a magic wand. Besides, it has more benefits than undo steps. Let&#8217;s learn more.</em></p><p>Before understanding <strong>distributed version control system&nbsp;, </strong>let&#8217;s take a look at types of Version Control System.</p><p>There are many version control systems out there. Often they are divided into two groups: &#8220;<strong>centralized</strong>&#8221; and &#8220;<strong>distributed</strong>&#8221;.</p><ul><li><p>Centralized Version Control System</p></li><li><p>Distributed Version Control System</p></li></ul><p><strong>Centralized Version Control System(CVCS)</strong></p><div class="captioned-image-container"><figure><a class="image-link image2" target="_blank" href="https://substackcdn.com/image/fetch/$s_!c5gA!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F48b91d18-6eb3-40b4-9c4a-410bc230a0b3_800x353.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!c5gA!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F48b91d18-6eb3-40b4-9c4a-410bc230a0b3_800x353.png 424w, https://substackcdn.com/image/fetch/$s_!c5gA!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F48b91d18-6eb3-40b4-9c4a-410bc230a0b3_800x353.png 848w, https://substackcdn.com/image/fetch/$s_!c5gA!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F48b91d18-6eb3-40b4-9c4a-410bc230a0b3_800x353.png 1272w, https://substackcdn.com/image/fetch/$s_!c5gA!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F48b91d18-6eb3-40b4-9c4a-410bc230a0b3_800x353.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!c5gA!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F48b91d18-6eb3-40b4-9c4a-410bc230a0b3_800x353.png" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/48b91d18-6eb3-40b4-9c4a-410bc230a0b3_800x353.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:null,&quot;width&quot;:null,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:null,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:null,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:null,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!c5gA!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F48b91d18-6eb3-40b4-9c4a-410bc230a0b3_800x353.png 424w, https://substackcdn.com/image/fetch/$s_!c5gA!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F48b91d18-6eb3-40b4-9c4a-410bc230a0b3_800x353.png 848w, https://substackcdn.com/image/fetch/$s_!c5gA!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F48b91d18-6eb3-40b4-9c4a-410bc230a0b3_800x353.png 1272w, https://substackcdn.com/image/fetch/$s_!c5gA!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F48b91d18-6eb3-40b4-9c4a-410bc230a0b3_800x353.png 1456w" sizes="100vw" loading="lazy"></picture><div></div></div></a></figure></div><p>Centralized version control systems are based on the idea that there is a single &#8220;central&#8221; copy of your project somewhere (probably on a server), and programmers will &#8220;commit&#8221; their changes to this central copy.</p><p>&#8220;Committing&#8221; a change simply means recording the change in the central system. Other programmers can then see this change. They can also pull down the change, and the version control tool will automatically update the contents of any files that were changed.</p><p><strong>Drawbacks of CVCS</strong></p><ul><li><p>It is not locally available, which means we must connect to the network to perform operations.</p></li><li><p>During the operations, if the central server gets crashed, there is a high chance of losing the data.</p></li><li><p>For every command, CVCS connects the central server which impacts speed of operation</p></li></ul><p>&#8203;The <strong>Distributed Version Control System</strong> is developed to overcome all these issues.</p><p><strong>Distributed Version Control System(DVCS)</strong></p><div class="captioned-image-container"><figure><a class="image-link image2" target="_blank" href="https://substackcdn.com/image/fetch/$s_!sghy!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9fa4010e-afec-437f-9e1f-62ca46d711e9_800x529.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!sghy!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9fa4010e-afec-437f-9e1f-62ca46d711e9_800x529.png 424w, https://substackcdn.com/image/fetch/$s_!sghy!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9fa4010e-afec-437f-9e1f-62ca46d711e9_800x529.png 848w, https://substackcdn.com/image/fetch/$s_!sghy!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9fa4010e-afec-437f-9e1f-62ca46d711e9_800x529.png 1272w, https://substackcdn.com/image/fetch/$s_!sghy!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9fa4010e-afec-437f-9e1f-62ca46d711e9_800x529.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!sghy!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9fa4010e-afec-437f-9e1f-62ca46d711e9_800x529.png" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/9fa4010e-afec-437f-9e1f-62ca46d711e9_800x529.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:null,&quot;width&quot;:null,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:null,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:null,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:null,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!sghy!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9fa4010e-afec-437f-9e1f-62ca46d711e9_800x529.png 424w, https://substackcdn.com/image/fetch/$s_!sghy!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9fa4010e-afec-437f-9e1f-62ca46d711e9_800x529.png 848w, https://substackcdn.com/image/fetch/$s_!sghy!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9fa4010e-afec-437f-9e1f-62ca46d711e9_800x529.png 1272w, https://substackcdn.com/image/fetch/$s_!sghy!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9fa4010e-afec-437f-9e1f-62ca46d711e9_800x529.png 1456w" sizes="100vw" loading="lazy"></picture><div></div></div></a></figure></div><p>In distributed version control most of the mechanism or model applies the same as centralized. The only major difference you will find here is, instead of one single repository which is the server, here every single developer or client has their own server and they will have a copy of the entire history or version of the code and all of its branches in their local server or machine. Basically, every client or user can work locally and disconnected which is more convenient than centralized source control and that&#8217;s why it is called distributed.</p><p>It doesn&#8217;t follow the way of communicating or merging the code straight forward to the master repository after making changes. Firstly you commit all the changes in your own server or repository and then the &#8216;set of changes&#8217; will merge to the master repository.</p><h3>Some Basic Commands to use&nbsp;GIT</h3><h4>Getting a Git Repository</h4><p>There are two ways to obtain a Git repository&nbsp;:</p><ol><li><p>You can take a local directory that is currently not under version control, and turn it into a Git repository, or</p></li><li><p>You can <strong>clone</strong> an existing Git repository from elsewhere.</p></li></ol><p>In either case, you end up with a Git repository on your local machine, ready for work.</p><h4><strong>Initializing a Repository in an Existing Directory</strong></h4><p>To create a new repo, you&#8217;ll use the <code>git init</code> command. <code>git init</code> is a one-time command you use during the initial setup of a new repo. Executing this command will create a new&nbsp;<code>.git</code> subdirectory in your current working directory. This will also create a new main branch.</p><pre><code>$ git init</code></pre><h4>Cloning an Existing Repository</h4><p>If a project has already been set up in a central repository, the clone command is the most common way for users to obtain a local development clone. Like <code>git init</code>, cloning is generally a one-time operation. Once a developer has obtained a working copy, all version control operations are managed through their local repository.</p><pre><code>$ git clone &lt;repo url&gt;</code></pre><h4>Recording Changes to the Repository</h4><div class="captioned-image-container"><figure><a class="image-link image2" target="_blank" href="https://substackcdn.com/image/fetch/$s_!fAmZ!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff314f2ae-b76e-45da-9997-ac5b1c0a17d5_800x330.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!fAmZ!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff314f2ae-b76e-45da-9997-ac5b1c0a17d5_800x330.png 424w, https://substackcdn.com/image/fetch/$s_!fAmZ!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff314f2ae-b76e-45da-9997-ac5b1c0a17d5_800x330.png 848w, https://substackcdn.com/image/fetch/$s_!fAmZ!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff314f2ae-b76e-45da-9997-ac5b1c0a17d5_800x330.png 1272w, https://substackcdn.com/image/fetch/$s_!fAmZ!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff314f2ae-b76e-45da-9997-ac5b1c0a17d5_800x330.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!fAmZ!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff314f2ae-b76e-45da-9997-ac5b1c0a17d5_800x330.png" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/f314f2ae-b76e-45da-9997-ac5b1c0a17d5_800x330.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:null,&quot;width&quot;:null,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:null,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:null,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:null,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!fAmZ!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff314f2ae-b76e-45da-9997-ac5b1c0a17d5_800x330.png 424w, https://substackcdn.com/image/fetch/$s_!fAmZ!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff314f2ae-b76e-45da-9997-ac5b1c0a17d5_800x330.png 848w, https://substackcdn.com/image/fetch/$s_!fAmZ!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff314f2ae-b76e-45da-9997-ac5b1c0a17d5_800x330.png 1272w, https://substackcdn.com/image/fetch/$s_!fAmZ!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff314f2ae-b76e-45da-9997-ac5b1c0a17d5_800x330.png 1456w" sizes="100vw" loading="lazy"></picture><div></div></div></a></figure></div><p>Remember that each file in your working directory can be in one of two states: <strong>tracked</strong> or <strong>untracked</strong>. Tracked files are files that were in the last snapshot, as well as any newly staged files; they can be unmodified, modified, or staged. In short, tracked files are files that Git knows about.</p><p>Untracked files are everything else&#8202;&#8212;&#8202;any files in your working directory that were not in your last snapshot and are not in your staging area. When you first clone a repository, all of your files will be tracked and unmodified because Git just checked them out and you haven&#8217;t edited anything.</p><p>As you edit files, Git sees them as modified, because you&#8217;ve changed them since your last commit. As you work, you selectively stage these modified files and then commit all those staged changes, and the cycle repeats.</p><h4>Checking the Status of Your&nbsp;Files</h4><p>The <code>git status</code> command displays the state of the working directory and the staging area. It lets you see which changes have been staged, which haven&#8217;t, and which files aren&#8217;t being tracked by Git.</p><pre><code>$ git status
On branch master
Your branch is up-to-date with 'origin/master'.
nothing to commit, working tree clean</code></pre><p>This means you have a clean working directory; in other words, none of your tracked files are modified. Git also doesn&#8217;t see any untracked files, or they would be listed here. Finally, the command tells you which branch you&#8217;re on.</p><h4>Saving changes</h4><ul><li><p>git add</p></li><li><p>git commit</p></li><li><p>git diff</p></li><li><p>git stash</p></li></ul><h4>git add</h4><p>The <code>git add</code> command adds a change in the working directory to the staging area. It tells Git that you want to include updates to a particular file in the next commit. However, <code>git add</code> doesn't really affect the repository in any significant way&#8212;changes are not actually recorded until you run <code>git commit</code>.</p><pre><code>$ git add &lt;file&gt; 
// Stage all changes in &lt;file&gt; for the next commit.</code></pre><pre><code>$ git add &lt;directory&gt;
// Stage all changes in &lt;directory&gt; for the next commit.</code></pre><h4>git commit</h4><p>The <code>git commit</code> command captures a snapshot of the project's currently staged changes. Committed snapshots can be thought of as &#8220;safe&#8221; versions of a project&#8212;Git will never change them unless you explicitly ask it to. Prior to the execution of <code>git commit</code>, The <code>git add</code> command is used to promote or 'stage' changes to the project that will be stored in a commit.</p><pre><code>$ git commit -m "commit message"</code></pre><h4>git diff</h4><p><code>git status</code> command is too vague for you&#8202;&#8212;&#8202;you want to know exactly what you changed, not just which files were changed&#8202;&#8212;&#8202;you can use the <code>git diff</code> command. You&#8217;ll probably use it most often to answer these two questions: What have you changed but not yet staged? And what have you staged that you are about to commit? Although <code>git status</code> answers those questions very generally by listing the file names, <code>git diff</code> shows you the exact lines added and removed&#8202;&#8212;&#8202;the patch, as it were.</p><p>To see what you&#8217;ve changed but not yet staged, type <code>git diff</code> with no other arguments:</p><pre><code>$ git diff</code></pre><p>That command compares what is in your working directory with what is in your staging area. The result tells you the changes you&#8217;ve made that you haven&#8217;t yet staged.</p><p>You can use <code>git diff --staged</code>. This command compares your staged changes to your last commit:</p><pre><code>$ git diff --staged</code></pre><h4>git stash</h4><p>Often, when you&#8217;ve been working on part of your project, things are in a messy state and you want to switch branches for a bit to work on something else. The problem is, you don&#8217;t want to do a commit of half-done work just so you can get back to this point later. The answer to this issue is the <code>git stash</code> command.</p><p>Stashing takes the dirty state of your working directory&#8202;&#8212;&#8202;that is, your modified tracked files and staged changes&#8202;&#8212;&#8202;and saves it on a stack of unfinished changes that you can reapply at any time (even on a different branch).</p><pre><code>$ git stash
Saved working directory and index state \
  "WIP on master: 049d078 Create index file"
HEAD is now at 049d078 Create index file
(To restore them type "git stash apply")</code></pre><p>You can reapply the one you just stashed by using the command&nbsp;: git stash apply</p><pre><code>$ git stash apply
On branch master
Changes not staged for commit:
  (use "git add &lt;file&gt;..." to update what will be committed)
  (use "git checkout -- &lt;file&gt;..." to discard changes in working directory)

&#9;modified:   index.html
&#9;modified:   lib/simplegit.rb

no changes added to commit (use "git add" and/or "git commit -a")</code></pre><p>Thank you, for reading this post&nbsp;, hope you liked it please give an applause.</p>]]></content:encoded></item><item><title><![CDATA[S.O.L.I.D. Principals]]></title><description><![CDATA[Introduction]]></description><link>https://sanjayofficial.substack.com/p/s-o-l-i-d-principals-41a5b3b604eb</link><guid isPermaLink="false">https://sanjayofficial.substack.com/p/s-o-l-i-d-principals-41a5b3b604eb</guid><dc:creator><![CDATA[Sanjay Mehta]]></dc:creator><pubDate>Thu, 02 Sep 2021 15:24:47 GMT</pubDate><enclosure url="https://substack-post-media.s3.amazonaws.com/public/images/db6bffa1-195d-4405-bc9d-b82a07dc7305_800x368.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<div class="captioned-image-container"><figure><a class="image-link image2" target="_blank" href="https://substackcdn.com/image/fetch/$s_!jMWu!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F91fbb9e7-efd6-4f66-8883-73cae7517d9a_800x368.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!jMWu!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F91fbb9e7-efd6-4f66-8883-73cae7517d9a_800x368.png 424w, https://substackcdn.com/image/fetch/$s_!jMWu!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F91fbb9e7-efd6-4f66-8883-73cae7517d9a_800x368.png 848w, https://substackcdn.com/image/fetch/$s_!jMWu!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F91fbb9e7-efd6-4f66-8883-73cae7517d9a_800x368.png 1272w, https://substackcdn.com/image/fetch/$s_!jMWu!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F91fbb9e7-efd6-4f66-8883-73cae7517d9a_800x368.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!jMWu!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F91fbb9e7-efd6-4f66-8883-73cae7517d9a_800x368.png" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/91fbb9e7-efd6-4f66-8883-73cae7517d9a_800x368.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:null,&quot;width&quot;:null,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:null,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:null,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:null,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!jMWu!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F91fbb9e7-efd6-4f66-8883-73cae7517d9a_800x368.png 424w, https://substackcdn.com/image/fetch/$s_!jMWu!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F91fbb9e7-efd6-4f66-8883-73cae7517d9a_800x368.png 848w, https://substackcdn.com/image/fetch/$s_!jMWu!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F91fbb9e7-efd6-4f66-8883-73cae7517d9a_800x368.png 1272w, https://substackcdn.com/image/fetch/$s_!jMWu!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F91fbb9e7-efd6-4f66-8883-73cae7517d9a_800x368.png 1456w" sizes="100vw" fetchpriority="high"></picture><div></div></div></a></figure></div><h3><strong>Introduction</strong></h3><p><em><strong>SOLID</strong></em> is an acronym for the first five object-oriented design (OOD) principles by Robert C. Martin (also known as <a href="http://en.wikipedia.org/wiki/Robert_Cecil_Martin">Uncle Bob</a>).</p><p><strong>SOLID</strong> stands for:</p><ul><li><p><strong>S</strong>&#8202;&#8212;&#8202;Single Responsibility Principle</p></li><li><p><strong>O</strong>&#8202;&#8212;&#8202;Open-closed Principle</p></li><li><p><strong>L</strong>&#8202;&#8212;&#8202;Liskov Substitution Principle</p></li><li><p><strong>I</strong>&#8202;&#8212;&#8202;Interface Segregation Principle</p></li><li><p><strong>D</strong>&#8202;&#8212;&#8202;Dependency Inversion Principle</p></li></ul><h3>Why use the Solid Principles of&nbsp;OOP?</h3><ul><li><p>Object Oriented Programming is a powerful concept.</p></li><li><p>But, OOP doesn&#8217;t always lead to quality software.</p></li><li><p>The five principles focus on dependency management.</p></li><li><p>Poor Dependency Management leads to code that is brittle, fragile, and hard to change.</p></li><li><p>Proper dependency management leads to quality code that is easy to maintain.</p></li></ul><h3>Single Responsibility Principle</h3><div class="captioned-image-container"><figure><a class="image-link image2" target="_blank" href="https://substackcdn.com/image/fetch/$s_!ZWFo!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F60448467-454d-427d-acfa-b4115a59913a_639x463.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!ZWFo!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F60448467-454d-427d-acfa-b4115a59913a_639x463.png 424w, https://substackcdn.com/image/fetch/$s_!ZWFo!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F60448467-454d-427d-acfa-b4115a59913a_639x463.png 848w, https://substackcdn.com/image/fetch/$s_!ZWFo!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F60448467-454d-427d-acfa-b4115a59913a_639x463.png 1272w, https://substackcdn.com/image/fetch/$s_!ZWFo!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F60448467-454d-427d-acfa-b4115a59913a_639x463.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!ZWFo!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F60448467-454d-427d-acfa-b4115a59913a_639x463.png" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/60448467-454d-427d-acfa-b4115a59913a_639x463.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:null,&quot;width&quot;:null,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:null,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:null,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:null,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!ZWFo!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F60448467-454d-427d-acfa-b4115a59913a_639x463.png 424w, https://substackcdn.com/image/fetch/$s_!ZWFo!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F60448467-454d-427d-acfa-b4115a59913a_639x463.png 848w, https://substackcdn.com/image/fetch/$s_!ZWFo!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F60448467-454d-427d-acfa-b4115a59913a_639x463.png 1272w, https://substackcdn.com/image/fetch/$s_!ZWFo!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F60448467-454d-427d-acfa-b4115a59913a_639x463.png 1456w" sizes="100vw"></picture><div></div></div></a></figure></div><p><strong>Single Responsibility Principle states that</strong></p><p><em>A class should have one and only one reason to change, meaning that a class should have only one job.</em></p><ul><li><p>Every class should have a single responsibility.</p></li><li><p>Classes should be small. No more than a screen full of code.</p></li><li><p>Avoid <strong>GOD</strong> classes</p></li><li><p>Split big classes into smaller classes.</p></li></ul><p>Let&#8217;s understand with the help of code.</p><pre><code>public class SimpleCalculator{</code></pre><pre><code>  public int add(int a , int b){
      return a + b;
  }</code></pre><pre><code>  public int subtract(int a , int b){
      return a - b;
  }</code></pre><pre><code>  public int multiply(int a , int b){
      return a * b;
  }</code></pre><pre><code>  public int divide(int a , int b){
      return a/b;
  }
  
  public void printSum(int sum){
      System.out.println(s);
  }</code></pre><pre><code>}</code></pre><p>The Simple calculator class violates the rule of SRP. As per the rule a class should have one job to do but the Simple calculator class have two responsibilities <strong>calculating</strong> and <strong>printing</strong> the value.</p><p>We should create another class ValuePrinter that handles only printing the value.</p><pre><code>public class ValuePrinter{</code></pre><pre><code>public void printSum(int value){
      System.out.println(value);
  }</code></pre><pre><code>}</code></pre><pre><code>public class SimpleCalculator{</code></pre><pre><code>public int add(int a , int b){
      return a + b;
  }</code></pre><pre><code>public int subtract(int a , int b){
      return a - b;
  }</code></pre><pre><code>public int multiply(int a , int b){
      return a * b;
  }</code></pre><pre><code>public int divide(int a , int b){
      return a/b;
  }
}</code></pre><p>That satisfies the single-responsibility principle.</p><h3>Open-Closed Principal</h3><div class="captioned-image-container"><figure><a class="image-link image2" target="_blank" href="https://substackcdn.com/image/fetch/$s_!5lUB!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Facc56416-17d4-4f38-8c76-024cefac6212_800x229.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!5lUB!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Facc56416-17d4-4f38-8c76-024cefac6212_800x229.png 424w, https://substackcdn.com/image/fetch/$s_!5lUB!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Facc56416-17d4-4f38-8c76-024cefac6212_800x229.png 848w, https://substackcdn.com/image/fetch/$s_!5lUB!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Facc56416-17d4-4f38-8c76-024cefac6212_800x229.png 1272w, https://substackcdn.com/image/fetch/$s_!5lUB!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Facc56416-17d4-4f38-8c76-024cefac6212_800x229.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!5lUB!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Facc56416-17d4-4f38-8c76-024cefac6212_800x229.png" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/acc56416-17d4-4f38-8c76-024cefac6212_800x229.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:null,&quot;width&quot;:null,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:null,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:null,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:null,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!5lUB!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Facc56416-17d4-4f38-8c76-024cefac6212_800x229.png 424w, https://substackcdn.com/image/fetch/$s_!5lUB!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Facc56416-17d4-4f38-8c76-024cefac6212_800x229.png 848w, https://substackcdn.com/image/fetch/$s_!5lUB!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Facc56416-17d4-4f38-8c76-024cefac6212_800x229.png 1272w, https://substackcdn.com/image/fetch/$s_!5lUB!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Facc56416-17d4-4f38-8c76-024cefac6212_800x229.png 1456w" sizes="100vw" loading="lazy"></picture><div></div></div></a></figure></div><p><strong>Open-Closed principle states that</strong></p><p><em>Objects or entities should be open for extension but closed for modification.</em></p><ul><li><p>Classes should be open for extension.</p></li><li><p>But close for modification.</p></li><li><p>You should be able to extend a classes behavior, without modifying it.</p></li><li><p>Use private variables with getters and setters -ONLY when you need them.</p></li><li><p>Use abstract base classes.</p></li></ul><p>Consider an insurance system that validates health insurance claims before approving one. A <strong>HealthInsuranceSurveyor</strong> class responsible to validate claims and a <strong>ClaimApprovalManager</strong> class responsible to approve claims.</p><pre><code>public class HealthInsuranceSurveyor{</code></pre><pre><code>public boolean isValidClaim(){
    System.out.println("HealthInsuranceSurveyor: Validating health insurance claim...");
  
   return true;</code></pre><pre><code> }</code></pre><pre><code>public class ClaimApprovalManager{</code></pre><pre><code>public void processHeathClaim(HealthInsuranceSurveyor surveyor){
       if(surveyor.isValidClaim()){
           System.out.println("ClaimApprovalManager : Valid claim. 
Currently processing claim for approval....");</code></pre><pre><code>      }</code></pre><pre><code>  }</code></pre><pre><code>}</code></pre><p>Both the <strong>HealthInsuranceSurveyor</strong> and <strong>ClaimApprovalManager</strong> classes work fine and the design for the insurance system appears perfect until a new requirement to process vehicle insurance claims arises.We now need to include a new <strong>VehicleInsuranceSurveyor</strong> class, and this should not create any problems. But, what we also need is to modify the <strong>ClaimApprovalManager</strong> class to process vehicle insurance claims. This is how the modified <strong>ClaimApprovalManager</strong> will be:</p><h4>Modified ClaimApprovalManager.java</h4><pre><code>public class ClaimApprovalManager{</code></pre><pre><code>public void processHeathClaim(HealthInsuranceSurveyor surveyor){
       if(surveyor.isValidClaim()){
           System.out.println("ClaimApprovalManager : Valid claim. 
Currently processing claim for approval....");</code></pre><pre><code>}
}
public void processVehicleClaim(VehicleInsuranceSurveyor surveyor){
     if(surveyor.isValidClaim()){
           System.out.println("ClaimApprovalManager : Valid claim. 
Currently processing claim for approval....");
}
}
}</code></pre><p>In the example above, we modified the <strong>ClaimApprovalManager</strong> class by adding a new <strong>processVehicleClaim</strong>( ) method to incorporate a new functionality (claim approval of vehicle insurance).This is a clear violation of the Open Closed Principle.</p><p>The ideal approach for the insurance claim example would have been to design the ClaimApprovalManager class in a way that it remains:</p><ul><li><p><strong>Open</strong> to support more types of insurance claims.</p></li><li><p><strong>Closed</strong> for any modifications whenever support for a new type of claim is added.</p></li></ul><p>To achieve this, let&#8217;s introduce a layer of abstraction by creating an abstract class to represent different claim validation behaviors. We will name the class InsuranceSurveyor.</p><h4>InsuranceSurveyor.java</h4><pre><code>public abstract class InsuranceSurveyor{
  public abstract boolean isValidClaim();
}</code></pre><h4>HealthInsuranceSurveyor.java</h4><pre><code>public class HealthInsuranceSurveyor extends InsuranceSurveyor{</code></pre><pre><code>public boolean isValidClaim(){
    System.out.println("HealthInsuranceSurveyor: Validating health insurance claim...");
  
   return true;</code></pre><pre><code>}</code></pre><h4>VehicleInsuranceSurveyor.java</h4><pre><code>public class VehicleInsuranceSurveyor extends InsuranceSurveyor{</code></pre><pre><code>public boolean isValidClaim(){
    System.out.println("VehicleInsuranceSurveyor: Validating vehicle insurance claim...");
  
   return true;</code></pre><pre><code>}</code></pre><h4>ClaimApprovalManager.java</h4><pre><code>public class ClaimApprovalManager{</code></pre><pre><code>public void processHeathClaim(InsuranceSurveyor surveyor){
       if(surveyor.isValidClaim()){
           System.out.println("ClaimApprovalManager : Valid claim. 
Currently processing claim for approval....");
}
}
}</code></pre><p>In the example above, we wrote a processClaim( ) method to accept a InsuranceSurveyor type instead of specifying a concrete type. In this way, any further addition of InsuranceSurveyor implementations will not affect the ClaimApprovalManager class. Our insurance system is now <strong>open</strong> to support more types of insurance claims, and <strong>closed</strong> for any modifications whenever a new claim type is added.</p><h3>Liskov Substitution Principle</h3><div class="captioned-image-container"><figure><a class="image-link image2" target="_blank" href="https://substackcdn.com/image/fetch/$s_!1aWP!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4ba3b1b2-94dc-4150-9bd3-9ed182136ce3_656x507.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!1aWP!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4ba3b1b2-94dc-4150-9bd3-9ed182136ce3_656x507.png 424w, https://substackcdn.com/image/fetch/$s_!1aWP!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4ba3b1b2-94dc-4150-9bd3-9ed182136ce3_656x507.png 848w, https://substackcdn.com/image/fetch/$s_!1aWP!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4ba3b1b2-94dc-4150-9bd3-9ed182136ce3_656x507.png 1272w, https://substackcdn.com/image/fetch/$s_!1aWP!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4ba3b1b2-94dc-4150-9bd3-9ed182136ce3_656x507.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!1aWP!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4ba3b1b2-94dc-4150-9bd3-9ed182136ce3_656x507.png" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/4ba3b1b2-94dc-4150-9bd3-9ed182136ce3_656x507.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:null,&quot;width&quot;:null,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:null,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:null,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:null,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!1aWP!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4ba3b1b2-94dc-4150-9bd3-9ed182136ce3_656x507.png 424w, https://substackcdn.com/image/fetch/$s_!1aWP!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4ba3b1b2-94dc-4150-9bd3-9ed182136ce3_656x507.png 848w, https://substackcdn.com/image/fetch/$s_!1aWP!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4ba3b1b2-94dc-4150-9bd3-9ed182136ce3_656x507.png 1272w, https://substackcdn.com/image/fetch/$s_!1aWP!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4ba3b1b2-94dc-4150-9bd3-9ed182136ce3_656x507.png 1456w" sizes="100vw" loading="lazy"></picture><div></div></div></a></figure></div><p><em>The principal defines that objects of a superclass shall be replaceable with object of its subclasses without breaking the application.</em></p><ul><li><p>That requires the objects of your subclasses to behave in the same way as the objects of your superclass.</p></li><li><p>It means that we must make sure that new derived classes are extending the base classes without changing their behavior.</p></li><li><p>It is an extension of Open Closed Principal.</p></li><li><p>This principal helps you to implement OCP correctly.</p></li></ul><p>Let&#8217;s take an example to understand it better</p><ol><li><p>Calculate Area of Rectangle.</p></li><li><p>Calculate Area of Square as well</p></li></ol><p>As we know, <strong>Square is a Rectangle</strong> and if we talk about inheritance it is also be read as &#8220;<strong>IS A</strong>&#8221; relationship.</p><p>So, we can create Rectangle as a base or super class and Square as sub class.</p><p><strong>Rectangle.java</strong></p><pre><code>public class Rectangle {</code></pre><pre><code> protected int width;
 protected int height;</code></pre><pre><code>public int getWidth(){
   return this.width;
 }</code></pre><pre><code>public int getHeight(){
   return this.height;
 }
 
public void setHeight(int height){
  this.height = height;
}</code></pre><pre><code>public void setWidth(int width){
  this.width = width;
}</code></pre><pre><code>public int getArea(){
 return this.height * this.width;
}
}</code></pre><p><strong>Square.java</strong></p><pre><code>public class Square extends Rectangle{ 
 
public void setHeight(int height){
  this.height = height;
  this.width = height;</code></pre><pre><code>}</code></pre><pre><code>public void setWidth(int width){
  this.width = width;
  this.height = width;
}
}</code></pre><p><strong>CalculateRectangleArea.java</strong></p><pre><code>public class CalculateRectangleArea{</code></pre><pre><code>public static void main(String[] args){
   
  Rectangle rect = new Rectangle();
  rect.setWidth(2);
  rect.setHeight(3);</code></pre><pre><code>  System.out.println("Area of rectangle : " + rect.getArea());</code></pre><pre><code>}
}</code></pre><pre><code>Output : 
Area of rectangle : 6</code></pre><p><strong>CalculateSquareArea.java</strong></p><pre><code>public class CalculateSquareArea{</code></pre><pre><code>public static void main(String[] args){
   
  Rectangle square = new Square();
  square.setWidth(2);
  square.setHeight(3);</code></pre><pre><code>System.out.println("Area of square: " + square.getArea());</code></pre><pre><code>}
}</code></pre><pre><code>Output : 
Area of square : 9</code></pre><p>Now, if we change the order of setWidth and setHeight method</p><pre><code>public class CalculateSquareArea{</code></pre><pre><code>public static void main(String[] args){
   
  Rectangle square = new Square();
  square.setHeight(3);
  square.setWidth(2);</code></pre><pre><code>System.out.println("Area of square is : " + square.getArea());</code></pre><pre><code>}
}</code></pre><pre><code>Output : 
Area of square is : 4</code></pre><p>The output after changing the order of method is not same&nbsp;, so the above code violates the LSP principle i.e &#8220; <em>The objects of your subclasses to behave in the same way as the objects of your superclass</em>&#8221;.</p><p><strong>How to identify violation of LSP.</strong></p><ul><li><p>A not implemented method in the subclass.</p></li><li><p>Subclass function overrides the base class method to give it new meaning.</p></li></ul><p>Let&#8217;s implement the LSP in the correct manner.</p><p><strong>Shape.java</strong></p><pre><code>public abstract class Shape {
 abstract public int getArea();
}</code></pre><p><strong>Rectangle.java</strong></p><pre><code>public class Rectangle extends Shape{</code></pre><pre><code>protected int width;
 protected int height;</code></pre><pre><code>public int getWidth(){
   return this.width;
 }</code></pre><pre><code>public int getHeight(){
   return this.height;
 }
 
public void setHeight(int height){
  this.height = height;
}</code></pre><pre><code>public void setWidth(int width){
  this.width = width;
}</code></pre><pre><code>@Override
public int getArea(){
 return this.height * this.width;
}
}</code></pre><p><strong>Square.java</strong></p><pre><code>public class Square extends Shape{</code></pre><pre><code>int length;</code></pre><pre><code>public int getLength(){
   return this.length;
 }
 
public void setLength(int length){
  this.length = length;
}</code></pre><pre><code>@Override
public int getArea(){
 return this.length * this.length;
}
}</code></pre><p><strong>CalculateRectangleArea.java</strong></p><pre><code>public class CalculateRectangleArea{</code></pre><pre><code>public static void main(String[] args){
   
  Shape rect = new Rectangle();
  rect.setWidth(2);
  rect.setHeight(3);</code></pre><pre><code>System.out.println("Area of rectangle : " + rect.getArea());</code></pre><pre><code>}
}</code></pre><pre><code>Output : 
Area of rectangle : 6</code></pre><p><strong>CalculateSquareArea.java</strong></p><pre><code>public class CalculateSquareArea{</code></pre><pre><code>public static void main(String[] args){
   
  Shape square = new Square();
  square.setLength(2);</code></pre><pre><code>System.out.println("Area of square : " + square.getArea());</code></pre><pre><code>}
}</code></pre><pre><code>Output : 
Area of square : 4</code></pre><p><strong>Why we shouldn&#8217;t violate LSP.</strong></p><ul><li><p>The use of using abstract base class is that, in future, you can write a new subclass and insert it into existing, working, tested code.</p></li><li><p>The essence of the Open Closed Principal.</p></li><li><p>However, when the subclasses don&#8217;t adhere properly to the behavior of the base class, you have to go through the existing code and modify the subclasses accordingly.</p></li><li><p>This is a blatant violation of the Open Closed Principal.</p></li></ul><h3>Interface Segregation Principle</h3><div class="captioned-image-container"><figure><a class="image-link image2" target="_blank" href="https://substackcdn.com/image/fetch/$s_!9bHi!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F76343499-9f01-4037-bd4d-5df9fad14c22_640x481.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!9bHi!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F76343499-9f01-4037-bd4d-5df9fad14c22_640x481.png 424w, https://substackcdn.com/image/fetch/$s_!9bHi!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F76343499-9f01-4037-bd4d-5df9fad14c22_640x481.png 848w, https://substackcdn.com/image/fetch/$s_!9bHi!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F76343499-9f01-4037-bd4d-5df9fad14c22_640x481.png 1272w, https://substackcdn.com/image/fetch/$s_!9bHi!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F76343499-9f01-4037-bd4d-5df9fad14c22_640x481.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!9bHi!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F76343499-9f01-4037-bd4d-5df9fad14c22_640x481.png" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/76343499-9f01-4037-bd4d-5df9fad14c22_640x481.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:null,&quot;width&quot;:null,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:null,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:null,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:null,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!9bHi!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F76343499-9f01-4037-bd4d-5df9fad14c22_640x481.png 424w, https://substackcdn.com/image/fetch/$s_!9bHi!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F76343499-9f01-4037-bd4d-5df9fad14c22_640x481.png 848w, https://substackcdn.com/image/fetch/$s_!9bHi!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F76343499-9f01-4037-bd4d-5df9fad14c22_640x481.png 1272w, https://substackcdn.com/image/fetch/$s_!9bHi!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F76343499-9f01-4037-bd4d-5df9fad14c22_640x481.png 1456w" sizes="100vw" loading="lazy"></picture><div></div></div></a></figure></div><p><em>This principle states that &#8220;Clients should not be forced to depend on methods that they do not use&#8221;. Here, the term &#8220;Clients&#8221; refers to the implementing classes of an interface.</em></p><p>The <strong>Interface Segregation Principle</strong> advocates segregating a &#8220;fat interface&#8221; into smaller and <a href="https://en.wikipedia.org/wiki/Cohesion_%28computer_science%29" title="Cohesion">highly cohesive</a> interfaces, known as &#8220;role interfaces&#8221;. Each &#8220;role interface&#8221; declares one or more methods for a specific behavior. Thus clients, instead of implementing a &#8220;fat interface&#8221;, can implement only those &#8220;role interfaces&#8221; whose methods are relevant to them.</p><h4>Interface Segregation Principle Violation (Bad Example):</h4><p>Let&#8217;s consider an example, the Athlete interface is an interface with some actions of an athlete:</p><pre><code>public interface Athlete {</code></pre><pre><code>void compete();</code></pre><pre><code>void swim();</code></pre><pre><code>void highJump();</code></pre><pre><code>void longJump();</code></pre><pre><code>}</code></pre><p>We have added the method compete, but also there some extra methods like <code>swim,</code> <code>highJump</code>&nbsp;, and <code>longJump</code>.</p><p>Suppose that John Doe is a swimming athlete. By implementing the Athlete interface, we have to implement methods like <code>highJump</code> and <code>longJump</code>, which JohnDoe will never use.</p><pre><code>public class JohnDoe implements Athlete {</code></pre><pre><code>@Override
    public void compete() {
        System.out.println("John Doe started competing");
    }</code></pre><pre><code>@Override
    public void swim() {
        System.out.println("John Doe started swimming");
    }</code></pre><pre><code>@Override
    public void highJump() {
    }</code></pre><pre><code>@Override
    public void longJump() {
    }
}</code></pre><p>The same problem will occur for another athlete who might be a field Athlete competing in the high jump and long jump.</p><p>We will follow the interface segregation principle and refactor the original interface:</p><pre><code>public interface Athlete {</code></pre><pre><code>void compete();
}</code></pre><p>Then we will create two other interfaces&#8202;&#8212;&#8202;one for Jumping athletes and one for Swimming athletes.</p><pre><code>public interface SwimmingAthlete extends Athlete {</code></pre><pre><code>void swim();</code></pre><pre><code>}</code></pre><pre><code>public interface JumpingAthlete extends Athlete {</code></pre><pre><code>void highJump();</code></pre><pre><code>void longJump();</code></pre><pre><code>}</code></pre><p>And therefore John Doe will not have to implement actions that he is not capable of performing:</p><pre><code>public class JohnDoe implements SwimmingAthlete {</code></pre><pre><code>@Override
    public void compete() {
        System.out.println("John Doe started competing");
    }</code></pre><pre><code>@Override
    public void swim() {
        System.out.println("John Doe started swimming");
    }</code></pre><pre><code>}</code></pre><h4>Summary of Interface Segregation Principle</h4><h3>Dependency Inversion Principle</h3><div class="captioned-image-container"><figure><a class="image-link image2" target="_blank" href="https://substackcdn.com/image/fetch/$s_!_jiO!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F143b02b7-eb9a-4004-8512-522ab6455f77_640x482.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!_jiO!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F143b02b7-eb9a-4004-8512-522ab6455f77_640x482.png 424w, https://substackcdn.com/image/fetch/$s_!_jiO!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F143b02b7-eb9a-4004-8512-522ab6455f77_640x482.png 848w, https://substackcdn.com/image/fetch/$s_!_jiO!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F143b02b7-eb9a-4004-8512-522ab6455f77_640x482.png 1272w, https://substackcdn.com/image/fetch/$s_!_jiO!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F143b02b7-eb9a-4004-8512-522ab6455f77_640x482.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!_jiO!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F143b02b7-eb9a-4004-8512-522ab6455f77_640x482.png" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/143b02b7-eb9a-4004-8512-522ab6455f77_640x482.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:null,&quot;width&quot;:null,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:null,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:null,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:null,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!_jiO!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F143b02b7-eb9a-4004-8512-522ab6455f77_640x482.png 424w, https://substackcdn.com/image/fetch/$s_!_jiO!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F143b02b7-eb9a-4004-8512-522ab6455f77_640x482.png 848w, https://substackcdn.com/image/fetch/$s_!_jiO!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F143b02b7-eb9a-4004-8512-522ab6455f77_640x482.png 1272w, https://substackcdn.com/image/fetch/$s_!_jiO!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F143b02b7-eb9a-4004-8512-522ab6455f77_640x482.png 1456w" sizes="100vw" loading="lazy"></picture><div></div></div></a></figure></div><p><em>High-level modules should not depend on low-level modules. Both should depend on abstractions.</em></p><p><em>High-level modules should not depend on low-level modules. Both should depend on abstractions.</em></p><ul><li><p>Entities must depend on abstractions, not on concretions.</p></li><li><p>This principle allows for decoupling.</p></li></ul><p>Here is an example of a <code>PasswordReminder</code> that connects to a MySQL database:</p><pre><code>class MySQLConnection
{
    public Connection connect()
    {
        // handle the database connection
        return 'Database connection';
    }
}</code></pre><pre><code>class PasswordReminder
{
    private MySQLConnection dbConnection;</code></pre><pre><code>public void construct(MySQLConnection dbConnection)
    {
        this.dbConnection = dbConnection;
    }
}</code></pre><p>First, the <code>MySQLConnection</code> is the low-level module while the <code>PasswordReminder</code> is high level, but according to the definition of <strong>D</strong> in SOLID, which states to <em>Depend on abstraction, not on concretions</em>. This snippet above violates this principle as the <code>PasswordReminder</code> class is being forced to depend on the <code>MySQLConnection</code> class.</p><p>Later, if you were to change the database engine, you would also have to edit the <code>PasswordReminder</code> class, and this would violate the <em>open-close principle</em>.</p><p>The <code>PasswordReminder</code> class should not care what database your application uses. To address these issues, you can code to an interface since high-level and low-level modules should depend on abstraction:</p><pre><code>interface DBConnectionInterface
{
    public Connection connect();
}</code></pre><p>The interface has a connect method and the <code>MySQLConnection</code> class implements this interface. Also, instead of directly type-hinting <code>MySQLConnection</code> class in the constructor of the <code>PasswordReminder</code>, you instead type-hint the <code>DBConnectionInterface</code> and no matter the type of database your application uses, the <code>PasswordReminder</code> class can connect to the database without any problems and open-close principle is not violated.</p><pre><code>class MySQLConnection implements DBConnectionInterface
{
    public Connection connect()
    {
        // handle the database connection
        return 'Database connection';
    }
}</code></pre><pre><code>class PasswordReminder
{
    private DBConnectionInterface dbConnection;</code></pre><pre><code>public void construct(DBConnectionInterface dbConnection)
    {
        this.dbConnection = dbConnection;
    }
}</code></pre><p>This code establishes that both the high-level and low-level modules depend on abstraction.</p><h3><strong>Conclusion</strong></h3><ul><li><p>The <strong>SOLID</strong> principals of OOP will lead you to better quality code which is more testable and easier to maintain.</p></li><li><p>A key theme is avoiding tight coupling in your code.</p></li></ul><p>Thanks for reading this blog. Happy Learning!!!</p>]]></content:encoded></item><item><title><![CDATA[Java Modularity]]></title><description><![CDATA[Modularity is a general concept which applies to the development of software in a fashion which allows individual modules to be developed&#8230;]]></description><link>https://sanjayofficial.substack.com/p/java-modularity-a848942d0820</link><guid isPermaLink="false">https://sanjayofficial.substack.com/p/java-modularity-a848942d0820</guid><dc:creator><![CDATA[Sanjay Mehta]]></dc:creator><pubDate>Sat, 21 Aug 2021 17:10:33 GMT</pubDate><enclosure url="https://substack-post-media.s3.amazonaws.com/public/images/4d023193-a48a-412c-9808-8798c438d419_518x180.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<div class="captioned-image-container"><figure><a class="image-link image2" target="_blank" href="https://substackcdn.com/image/fetch/$s_!IAy0!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fbfa9033b-34bb-4b0a-9573-8252e611ce61_518x180.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!IAy0!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fbfa9033b-34bb-4b0a-9573-8252e611ce61_518x180.png 424w, https://substackcdn.com/image/fetch/$s_!IAy0!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fbfa9033b-34bb-4b0a-9573-8252e611ce61_518x180.png 848w, https://substackcdn.com/image/fetch/$s_!IAy0!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fbfa9033b-34bb-4b0a-9573-8252e611ce61_518x180.png 1272w, https://substackcdn.com/image/fetch/$s_!IAy0!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fbfa9033b-34bb-4b0a-9573-8252e611ce61_518x180.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!IAy0!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fbfa9033b-34bb-4b0a-9573-8252e611ce61_518x180.png" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/bfa9033b-34bb-4b0a-9573-8252e611ce61_518x180.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:null,&quot;width&quot;:null,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:null,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:null,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:null,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!IAy0!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fbfa9033b-34bb-4b0a-9573-8252e611ce61_518x180.png 424w, https://substackcdn.com/image/fetch/$s_!IAy0!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fbfa9033b-34bb-4b0a-9573-8252e611ce61_518x180.png 848w, https://substackcdn.com/image/fetch/$s_!IAy0!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fbfa9033b-34bb-4b0a-9573-8252e611ce61_518x180.png 1272w, https://substackcdn.com/image/fetch/$s_!IAy0!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fbfa9033b-34bb-4b0a-9573-8252e611ce61_518x180.png 1456w" sizes="100vw" fetchpriority="high"></picture><div></div></div></a></figure></div><blockquote><p><strong>Modularity</strong> is a general concept which applies to the development of software in a fashion which allows individual <em>modules</em> to be developed, often with a standardized interface to allow modules to communicate. In fact, the kind of separation of concerns between objects in an OO language is much the same concept as for modules, except on a larger scale. Typically, partitioning a system into modules helps minimize <a href="http://en.wikipedia.org/wiki/Coupling_%28computer_science%29">coupling</a>, which should lead to easier to maintain code.</p></blockquote><h3>Why do we need Java modularity?</h3><p><strong>The JDK before Java SE 9</strong></p><p>1&nbsp;. The JDK was huge and monolithic.</p><p>2. This resulted in increased&#8230;<br>&#8202;&#8212;&#8202;Download Time<br>&#8202;&#8212;&#8202;Startup Time<br>&#8202;&#8212;&#8202;Memory Footprint</p><p><strong>The Modular JDK</strong></p><ol><li><p>With <strong>Java</strong> SE 9&nbsp;, the monolithic <strong>JDK</strong> was broken into 90 modules.</p></li></ol><p>2. Every module is a well defined piece of functionality.<br>&#8202;&#8212;&#8202;Similar packages and frameworks are grouped into their own modules.<br>&nbsp;For example: Logging&nbsp;, Swing and Instrumentation.<br>&#8202;&#8212;&#8202;Be aware of modules for significant API&nbsp;, not trivial ones.</p><p>3. Benefits Include:<br>&#8202;&#8212;&#8202;Applications which are more scalable to small devices.<br>&#8202;&#8212;&#8202;Improved application perfomance<br>&#8202;&#8212;&#8202;Improved security and maintainability(for Java and your apps)</p><p><strong>Listing the modules in Java 9</strong></p><pre><code>$java --list-modules</code></pre><h3><strong>Java SE&nbsp;Modules</strong></h3><p>These Modules are classified into two categories:</p><ol><li><p>Standard modules( java.* prefix for module names):<br>&#8202;&#8212;&#8202;Part of the Java SE specification<br>&#8202;&#8212;&#8202;For example: java.sql for database connectivity, java.xml for XML processing&nbsp;, and java.logging for logging</p></li><li><p>Modules not defined in the Java SE platform(jdk.* prefix for module names):<br>&#8202;&#8212;&#8202;Are specific to the JDK<br>&#8202;&#8212;&#8202;For example: jdk.jshell&nbsp;, jdk.policytool, jdk.httpserver</p></li></ol><h3>What&#8217;s Inside a&nbsp;Module?</h3><ul><li><p>A module is a set of exported packages and concealed packages.</p></li><li><p><strong>public</strong> no longer means &#8220;accessible to everyone&#8221;.</p></li><li><p>You may set up modules to encapsulate your own code.</p></li></ul><div class="captioned-image-container"><figure><a class="image-link image2" target="_blank" href="https://substackcdn.com/image/fetch/$s_!HOcF!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F712f8d26-6886-4829-a25f-5495c966f1a5_800x450.jpeg" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!HOcF!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F712f8d26-6886-4829-a25f-5495c966f1a5_800x450.jpeg 424w, https://substackcdn.com/image/fetch/$s_!HOcF!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F712f8d26-6886-4829-a25f-5495c966f1a5_800x450.jpeg 848w, https://substackcdn.com/image/fetch/$s_!HOcF!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F712f8d26-6886-4829-a25f-5495c966f1a5_800x450.jpeg 1272w, https://substackcdn.com/image/fetch/$s_!HOcF!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F712f8d26-6886-4829-a25f-5495c966f1a5_800x450.jpeg 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!HOcF!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F712f8d26-6886-4829-a25f-5495c966f1a5_800x450.jpeg" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/712f8d26-6886-4829-a25f-5495c966f1a5_800x450.jpeg&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:null,&quot;width&quot;:null,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:null,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:null,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:null,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!HOcF!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F712f8d26-6886-4829-a25f-5495c966f1a5_800x450.jpeg 424w, https://substackcdn.com/image/fetch/$s_!HOcF!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F712f8d26-6886-4829-a25f-5495c966f1a5_800x450.jpeg 848w, https://substackcdn.com/image/fetch/$s_!HOcF!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F712f8d26-6886-4829-a25f-5495c966f1a5_800x450.jpeg 1272w, https://substackcdn.com/image/fetch/$s_!HOcF!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F712f8d26-6886-4829-a25f-5495c966f1a5_800x450.jpeg 1456w" sizes="100vw" loading="lazy"></picture><div></div></div></a></figure></div><p><strong>Accessibility( JDK 9 and later)</strong></p><ul><li><p>public <strong>to everyone</strong></p></li><li><p>public, <strong>but only to specific modules</strong></p></li><li><p>public <strong>only within a module</strong></p></li><li><p>protected</p></li><li><p><strong>&lt;package&gt;</strong></p></li><li><p>private</p></li></ul><h3><strong>module-info.java</strong></h3><ul><li><p>A module is declared with a <strong>module-info.java</strong> file.</p></li><li><p>Declarations begin with the keyword <strong>module</strong>, followed by a unique module name and a module body enclosed in braces.</p></li><li><p>Add directives such as <strong>requires</strong>&nbsp;, <strong>exports</strong> to specify accessibility between modules.<br>&#8202;&#8212;&#8202;What packages the module makes available to other modules?<br>&#8202;&#8212;&#8202;Where a package is exported to?<br>&#8202;&#8212;&#8202;What outside modules it&#8217;s dependent on?</p></li></ul><pre><code>module modulename {</code></pre><pre><code>}</code></pre><h3>Creating a Modular&nbsp;Project</h3><ul><li><p>Name of the project</p></li><li><p>Place module-info.java in the root directory of the packages that you want to group as a module.</p></li><li><p>NetBeans marks this as the default package.</p></li><li><p>One modular JAR is produced for every module.</p></li></ul><p>&#8212; <strong>Modular</strong> JARs become the unit of release and reuse.</p><p>&#8212; They&#8217;re intended to contain a very specific set of functionality.</p><div class="captioned-image-container"><figure><a class="image-link image2" target="_blank" href="https://substackcdn.com/image/fetch/$s_!16wO!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F0cf52f6f-987c-43de-a6aa-f138e77a4bc2_304x289.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!16wO!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F0cf52f6f-987c-43de-a6aa-f138e77a4bc2_304x289.png 424w, https://substackcdn.com/image/fetch/$s_!16wO!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F0cf52f6f-987c-43de-a6aa-f138e77a4bc2_304x289.png 848w, https://substackcdn.com/image/fetch/$s_!16wO!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F0cf52f6f-987c-43de-a6aa-f138e77a4bc2_304x289.png 1272w, https://substackcdn.com/image/fetch/$s_!16wO!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F0cf52f6f-987c-43de-a6aa-f138e77a4bc2_304x289.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!16wO!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F0cf52f6f-987c-43de-a6aa-f138e77a4bc2_304x289.png" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/0cf52f6f-987c-43de-a6aa-f138e77a4bc2_304x289.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:null,&quot;width&quot;:null,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:null,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:null,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:null,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!16wO!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F0cf52f6f-987c-43de-a6aa-f138e77a4bc2_304x289.png 424w, https://substackcdn.com/image/fetch/$s_!16wO!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F0cf52f6f-987c-43de-a6aa-f138e77a4bc2_304x289.png 848w, https://substackcdn.com/image/fetch/$s_!16wO!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F0cf52f6f-987c-43de-a6aa-f138e77a4bc2_304x289.png 1272w, https://substackcdn.com/image/fetch/$s_!16wO!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F0cf52f6f-987c-43de-a6aa-f138e77a4bc2_304x289.png 1456w" sizes="100vw" loading="lazy"></picture><div></div></div></a><figcaption class="image-caption">Modules-Project</figcaption></figure></div><h3><strong>exports </strong>Module Directive</h3><ul><li><p>Declares a package is accessible to code in all other modules.<br>&#8202;&#8212;&#8202;Includes access to the package&#8217;s public classes&nbsp;, fields&nbsp;, and methods.<br>&#8202;&#8212;&#8202;Excludes access to anything with private&nbsp;, protected, or package access.</p></li><li><p>Use the exports statement judiciously.<br>&#8202;&#8212;&#8202;You&#8217;ll never be certain how someone else wants to use your module.<br>&#8202;&#8212;&#8202;Export only those packages that you feel are safe.<br>&#8202;&#8212;&#8202;Modularity is about future-proofing</p></li></ul><pre><code>module A {
  exports pkgA;</code></pre><pre><code>}</code></pre><h3>exports&#8230;to Module Directive</h3><ul><li><p>Declare a package is accessible to code in specific modules<br>&#8202;&#8212;&#8202;Includes access to the package&#8217;s public classes, fields, and methods<br>&#8202;&#8212;&#8202;Excludes access to anything with private, protected, or package access<br>&#8202;&#8212;&#8202;Excludes access from any module not specified</p></li><li><p>Use a specifies a comma-separated list to specify many modules to export to.</p></li><li><p>This is known as a qualified export.</p></li></ul><pre><code>module A {
    exports pkgA to B, C;
}</code></pre><h3>requires Module Directive</h3><ul><li><p>Declares the module is dependent on another module<br>&#8202;&#8212;&#8202;Only exported packages are readable by the requiring module.<br>&#8202;&#8212;&#8202;Packages that aren&#8217;t exported aren&#8217;t readable.<br>&#8202;&#8212;&#8202;Anything nonpublic is not readable, even from exported packages.</p></li><li><p>Classes within the current module may require a class, instance, or method written in another module.</p></li></ul><pre><code>module B {
    requires A;
}</code></pre><h3><strong>Example</strong></h3><pre><code>package pkgA;</code></pre><pre><code>public class ClassA{
  public int yearPublic = 2001;
  protected int yearProtected = 2002;
  int yearPackage = 2003;
  private int yearPrivate = 2004;
}</code></pre><pre><code>module A {
    exports pkgA;
}</code></pre><pre><code>module B {
   requires A;
}</code></pre><pre><code>package pkgB;</code></pre><pre><code>import pkgA.ClassA; </code></pre><pre><code>public class NewMain{
  public static void main(String[] args){
    ClassA test = new ClassA();
     System.out.println(test.yearPublic); //Yes
     System.out.println(test.yearProtected); //No
     System.out.println(test.yearPackage); //No
     System.out.println(test.yearPrivate); //No
}}</code></pre><h3>requires transitive Module Directive</h3><ul><li><p>Transitivity allows readability up the requirement chain.</p></li><li><p>Anything requiring the current module has access to:<br>&#8202;&#8212;&#8202;Packages exported by the current module<br>&#8202;&#8212;&#8202;Packages exported by anything the current module requires transitively</p></li><li><p>Known as &#8220;implied readability&#8221;</p></li></ul><h3>Example</h3><pre><code>module C{
  exports pkgC;
}

</code></pre><pre><code>package pkgC;</code></pre><pre><code>public class ClassC {
   public static String transitiveVar;
   transitiveVar = "From C";
}

</code></pre><pre><code>module A{
  requires transitive C;
  exports pkgA to B;
}

</code></pre><pre><code>module B {
   requires A;
}

</code></pre><pre><code>package pkgB;</code></pre><pre><code>import pkgA.ClassA;
import pkgC.ClassC;</code></pre><pre><code>public class NewMain{
  public static void main(String[] args){
    ClassA test = new ClassA();
    System.out.println(test.yearPublic);
    System.out.println(ClassC.transitiveVar);
}
}</code></pre><h3>The Base Module java.base</h3><ul><li><p>The base module exports all of the platform&#8217;s core packages.</p></li><li><p>Every module depends on <strong>java.base</strong>.</p></li><li><p><strong>java.base</strong> doesn&#8217;t depend on any other modules.</p></li><li><p>The<strong> java.base</strong> module reference is implicitly included in all other modules.</p></li></ul><pre><code>// module-info.java</code></pre><pre><code>module java.base{
  exports java.lang;
  exports java.io;
  exports java.net;
  exports java.util;
}</code></pre><pre><code>module A{
  requires java.base;   // implied
  requires java.logging;
  requires transitive C;
  exports pkgA to B;
}</code></pre><h3><strong>Summary of&nbsp;Keywords</strong></h3><p><strong>Keywords and Syntax with Description</strong></p><ol><li><p><strong>export &lt;package&gt;</strong><br>&#8202;&#8212;&#8202;Declares which package is eligible to be read.</p></li><li><p><strong>export &lt;package&gt; to &lt;module&gt;<br></strong>&#8202;&#8212;&#8202;Declares which package is eligible to be read by a specific module</p></li><li><p><strong>requires &lt;module&gt;<br>&#8202;</strong>&#8212;&#8202;Specifies another module to read from</p></li><li><p><strong>requires transitive &lt;module&gt;<br>&#8202;</strong>&#8212;&#8202;Specifies another module to read from. The relationship is transitive where indirect. access is given to modules requiring the current module.</p></li></ol><ul><li><p>These are restricted keywords</p></li><li><p>Their creation won&#8217;t break existing code.</p></li><li><p>They&#8217;re only available in the context of the <strong>module-info</strong> class.</p></li></ul><p>If you have questions or comments about this let me know in the comments below. You can view the full code here:</p><p><strong><a href="https://github.com/zsanjay/Java-9-Modules" title="https://github.com/zsanjay/Java-9-Modules">GitHub - zsanjay/Java-9-Modules</a></strong><a href="https://github.com/zsanjay/Java-9-Modules" title="https://github.com/zsanjay/Java-9-Modules"><br></a><em><a href="https://github.com/zsanjay/Java-9-Modules" title="https://github.com/zsanjay/Java-9-Modules">Contribute to zsanjay/Java-9-Modules development by creating an account on GitHub.</a></em><a href="https://github.com/zsanjay/Java-9-Modules" title="https://github.com/zsanjay/Java-9-Modules">github.com</a></p><p>Thanks for reading this blog. Happy Learning!!!</p>]]></content:encoded></item><item><title><![CDATA[Promise vs Observable]]></title><description><![CDATA[There has been an on-going debate in the world of developers, and that is which is better: JavaScript Promises or RxJS Observables? Each&#8230;]]></description><link>https://sanjayofficial.substack.com/p/promise-vs-observable-7c1af6fefd12</link><guid isPermaLink="false">https://sanjayofficial.substack.com/p/promise-vs-observable-7c1af6fefd12</guid><dc:creator><![CDATA[Sanjay Mehta]]></dc:creator><pubDate>Mon, 16 Aug 2021 19:48:14 GMT</pubDate><enclosure url="https://substack-post-media.s3.amazonaws.com/public/images/2bd58a38-8c88-4be3-b6aa-cff4b2f51dd4_800x379.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<div class="captioned-image-container"><figure><a class="image-link image2" target="_blank" href="https://substackcdn.com/image/fetch/$s_!SeXI!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2fd67169-8851-4477-a0c1-c79f37a8faef_800x379.jpeg" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!SeXI!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2fd67169-8851-4477-a0c1-c79f37a8faef_800x379.jpeg 424w, https://substackcdn.com/image/fetch/$s_!SeXI!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2fd67169-8851-4477-a0c1-c79f37a8faef_800x379.jpeg 848w, https://substackcdn.com/image/fetch/$s_!SeXI!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2fd67169-8851-4477-a0c1-c79f37a8faef_800x379.jpeg 1272w, https://substackcdn.com/image/fetch/$s_!SeXI!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2fd67169-8851-4477-a0c1-c79f37a8faef_800x379.jpeg 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!SeXI!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2fd67169-8851-4477-a0c1-c79f37a8faef_800x379.jpeg" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/2fd67169-8851-4477-a0c1-c79f37a8faef_800x379.jpeg&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:null,&quot;width&quot;:null,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:null,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:null,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:null,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!SeXI!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2fd67169-8851-4477-a0c1-c79f37a8faef_800x379.jpeg 424w, https://substackcdn.com/image/fetch/$s_!SeXI!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2fd67169-8851-4477-a0c1-c79f37a8faef_800x379.jpeg 848w, https://substackcdn.com/image/fetch/$s_!SeXI!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2fd67169-8851-4477-a0c1-c79f37a8faef_800x379.jpeg 1272w, https://substackcdn.com/image/fetch/$s_!SeXI!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2fd67169-8851-4477-a0c1-c79f37a8faef_800x379.jpeg 1456w" sizes="100vw" fetchpriority="high"></picture><div></div></div></a></figure></div><p>There has been an on-going debate in the world of developers, and that is which is better: JavaScript <strong>Promises</strong> or RxJS <strong>Observables</strong>? Each one can bring so much value to different projects. It&#8217;s a good idea to have a good understanding of each and how it could benefit a project. But before we start looking at some comparisons, let&#8217;s do a quick overview of what each one is.</p><h3><strong>What is a&nbsp;Promise</strong></h3><p>A <em><strong>promise</strong></em> is an object that encapsulates the result of an asynchronous operation.</p><p>Each promise has state, which can have one of the following values:</p><ul><li><p><em>Pending</em></p></li><li><p><em>Fulfilled</em> with a value</p></li><li><p><em>Rejected</em> for a reason</p></li></ul><p>The just created promise is in a <em>pending</em> state. The promise maintains the <em>pending</em> state as long as the asynchronous operation behind is in progress.</p><p>Then, depending on how the asynchronous operation completes, the promise state changes to either:</p><p>A) <em>fulfilled</em> (when the async operation completed successfully)</p><p>B) or <em>rejected</em> (when then async operation failed).</p><p>In JavaScript, you can create a promise object using a special constructor</p><pre><code>const promise = new Promise((resolve, reject) =&gt; {
  // Async operation logic here....
  if (asyncOperationSuccess) {
    resolve(value); // async operation successful
  } else {
    reject(error);  // async operation error
  }
});</code></pre><h3><strong>What is Observable</strong></h3><p><em><strong>Observable</strong></em> are just that&#8202;&#8212;&#8202;things you wish to observe and take action on. Angular uses the <strong>Observer pattern</strong> which simply means&#8202;&#8212;&#8202;Observable objects are registered, and other objects observe (in Angular using the subscribe method) them and take action when the observable object is acted on in some way.</p><p>To use observable, Angular uses a third-party library called Reactive Extensions (<strong>RxJS</strong>).</p><p>Let&#8217;s take a look how can we use <em><strong>Observable</strong></em> in our Angular application.</p><pre><code>import { Observable } from 'rxjs/Observable';</code></pre><pre><code>// Create simple observable that emits three values 
   const myObservable = Observable.of(1, 2, 3); </code></pre><pre><code>// Create observer object 
   const myObserver = { 
next: x =&gt; console.log('Observer got a next value: ' + x),             error: err =&gt; console.error('Observer got an error: ' + err),          complete: () =&gt; console.log('Observer got a complete notification')
 };         </code></pre><pre><code>// Execute with the observer object    myObservable.subscribe(myObserver);  </code></pre><pre><code>  // Logs:   
 // Observer got a next value: 1   
 // Observer got a next value: 2    
// Observer got a next value: 3    
// Observer got a complete notification</code></pre><p>Here are the main differences which is covered in this blog post:</p><h3>Eager vs&nbsp;Lazy</h3><p><strong>Promise is eager&nbsp;, </strong>hence<strong> </strong>execute immediately, and just once. The computation of the result is initiated when the promise is created. There is no way to restart work. All <code>then</code> clauses (subscriptions) share the same computation.</p><pre><code>const welcomePromise = new Promise(resolve =&gt; {  
console.log("In Promise executor fn"); 
 
 resolve("Welcome!");
}); </code></pre><pre><code>console.log("Before calling the then method");
 
welcomePromise.then(console.log); </code></pre><pre><code>// console output:
// In Promise executor fn
// Before calling the then method
// Welcome!</code></pre><p><strong>Observables</strong> is <strong>lazy</strong>&nbsp;, since not executed until a consumer subscribes. The <code>subscribe()</code> executes the defined behavior once, and it can be called again. Each subscription has its own computation. Resubscription causes recomputation of values.</p><pre><code>import { Observable } from "rxjs";</code></pre><pre><code>const welcomeObservable$ = new Observable(observer =&gt; {   console.log("In Observable producer fn"); </code></pre><pre><code>  observer.next("Welcome!"); 
  observer.complete();</code></pre><pre><code>}); 
console.log("Before calling the subscribe method"); welcomeObservable$.subscribe(console.log); </code></pre><pre><code>// console output:
// Before calling the subscribe method
// In Observable producer fn
// Welcome!</code></pre><h3><strong>Async vs&nbsp;Sync</strong></h3><p>Even if immediately resolved, the <strong>Promise</strong><em><strong> </strong></em><strong>is always asynchronous.</strong></p><pre><code>const welcomePromise = new Promise(resolve =&gt; {  
console.log("In Promise executor fn"); 
 
 resolve("Welcome!");
});</code></pre><pre><code>console.log("Before calling the then method");
 
welcomePromise.then(console.log);</code></pre><pre><code>console.log("After calling the then method"); </code></pre><pre><code>// console output:
// In Promise executor fn
// Before calling the then method
// After calling the then method
// Welcome!</code></pre><p>The <strong>Observables</strong> may be <strong>synchronous</strong> or <strong>asynchronous</strong></p><p><strong>Synchronous</strong></p><pre><code>import { Observable } from "rxjs";</code></pre><pre><code>const welcomeObservable = new Observable(observer =&gt; {   console.log("In Observable producer fn");</code></pre><pre><code>observer.next("Welcome!"); 
  observer.complete();</code></pre><pre><code>}); 
console.log("Before calling the subscribe method"); </code></pre><pre><code>welcomeObservable.subscribe(console.log);</code></pre><pre><code>// console output:
// Before calling the subscribe method
// In Observable producer fn
// Welcome!</code></pre><p><strong>Asynchronous</strong></p><pre><code>import { Observable } from "rxjs";</code></pre><pre><code>const asyncObservable = new Observable(observer =&gt; {   console.log("In Observable producer fn");</code></pre><pre><code>setTimeout(() =&gt; {</code></pre><pre><code>observer.next("Async!"); 
  observer.complete();</code></pre><pre><code>} , 1000)</code></pre><pre><code>}); 
console.log("Before calling the subscribe method");</code></pre><pre><code>asyncObservable.subscribe(console.log);</code></pre><pre><code>console.log("After calling the subscribe method");</code></pre><pre><code>// console output:
// Before calling the subscribe method
// In Observable producer fn
// After calling the subscribe method
// Async!</code></pre><h3><strong>Single vs Multiple&nbsp;values</strong></h3><p><strong>Promises</strong> are most commonly used to handle HTTP requests. In this model, you make a request and then wait for a single response. You can be sure that there won&#8217;t be multiple responses to the same request.</p><pre><code>const numberPromise = new Promise((resolve) =&gt; { 
resolve(5);
});</code></pre><pre><code> numberPromise.then(value =&gt; console.log(value));
// will simply print 5</code></pre><p><strong>Promise</strong> is always resolved with the first value passed to the <strong><code>resolve</code></strong> function and ignores further calls to it:</p><pre><code>const numberPromise = new Promise((resolve) =&gt; { 
resolve(5);
resolve(10);
});</code></pre><pre><code>numberPromise.then(value =&gt; console.log(value));
// still prints only 5</code></pre><p><strong>Observables</strong> allow you to resolve (or, as we say, &#8220;emit&#8221;) multiple values.</p><pre><code>const numberObservable = new Observable((observer) =&gt; {    observer.next(5);   
observer.next(10);
});</code></pre><pre><code>numberObservable.subscribe(value =&gt; console.log(value));
// prints 5 and 10</code></pre><h3>Cancellation</h3><p><strong>Observable</strong> subscriptions are cancellable. Unsubscribing removes the listener from receiving further values, and notifies the subscriber function to cancel work.</p><pre><code>const subscription = observable.subscribe(() =&gt; {</code></pre><pre><code>// observer handles notifications</code></pre><pre><code>});</code></pre><pre><code>subscription.unsubscribe();</code></pre><h4><strong>Promises</strong> are not cancellable.</h4><h3>Conclusions</h3><p>There are many differences between Observable and Promise. But the main differences are&nbsp;:</p><ul><li><p>The Observable<em> </em>is lazy whereas the Promise<em> </em>is eager</p></li><li><p>The Promise<em> </em>is always asynchronous, while the Observable<em> </em>can be either asynchronous or synchronous</p></li><li><p>The Promise<em> </em>can emit only a single value, whereas the Observable<em> </em>can emit single<em> or </em>multiple values.</p></li><li><p>The Observable<em> </em>subscriptions are cancellable whereas Promises are not cancellable.</p></li></ul><p>Thank you, for reading this post&nbsp;, hope you liked it please give an applause.</p>]]></content:encoded></item></channel></rss>