<?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"><channel><title><![CDATA[A Curious Coder]]></title><description><![CDATA[I'm a curious developer. I love to build things and share my insights on web development, distributed systems, programming, and compilers. Feel free to reach ou]]></description><link>https://blog.thecuriouscoder.in</link><generator>RSS for Node</generator><lastBuildDate>Wed, 15 Apr 2026 03:15:24 GMT</lastBuildDate><atom:link href="https://blog.thecuriouscoder.in/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Common Patterns of Dynamic Programming]]></title><description><![CDATA[Fibonacci Series




Problem LinkArticlesSolutions



Climbing StairsGithub

Fibonacci Series

Min Cost Climbing Stairs


Kadane’s Algorithm




Problem LinkArticlesSolutions



Maximum SubarrayGithub

Maximum Sum Circular Subarray

Maximum Product S...]]></description><link>https://blog.thecuriouscoder.in/common-patterns-of-dynamic-programming</link><guid isPermaLink="true">https://blog.thecuriouscoder.in/common-patterns-of-dynamic-programming</guid><category><![CDATA[Dynamic Programming]]></category><dc:creator><![CDATA[Subhasish Kundu]]></dc:creator><pubDate>Tue, 29 Jul 2025 12:51:42 GMT</pubDate><content:encoded><![CDATA[<h2 id="heading-fibonacci-series">Fibonacci Series</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Problem Link</strong></td><td><strong>Articles</strong></td><td><strong>Solutions</strong></td></tr>
</thead>
<tbody>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/climbing-stairs/description/">Climbing Stairs</a></td><td></td><td><a target="_blank" href="https://github.com/subhakundu/DsAlgoPractice/blob/main/DynamicProgramming/FibonacciSeries/ClimbingStairs/Solution.java">Github</a></td></tr>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/fibonacci-number/description/">Fibonacci Series</a></td><td></td><td></td></tr>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/min-cost-climbing-stairs/description/">Min Cost Climbing Stairs</a></td><td></td></tr>
</tbody>
</table>
</div><h2 id="heading-kadanes-algorithm">Kadane’s Algorithm</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Problem Link</strong></td><td><strong>Articles</strong></td><td><strong>Solutions</strong></td></tr>
</thead>
<tbody>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/maximum-subarray/description/">Maximum Subarray</a></td><td></td><td><a target="_blank" href="https://github.com/subhakundu/DsAlgoPractice/blob/main/DynamicProgramming/KadanesAlgorithm/MaximumSubarray/Solution.java">Github</a></td></tr>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/maximum-sum-circular-subarray/description/">Maximum Sum Circular Subarray</a></td><td></td><td></td></tr>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/maximum-product-subarray/description/">Maximum Product Subarray</a></td><td></td><td><a target="_blank" href="https://github.com/subhakundu/DsAlgoPractice/blob/main/DynamicProgramming/KadanesAlgorithm/MaximumProductSubarray/Solution.java">Github</a></td></tr>
</tbody>
</table>
</div><h2 id="heading-edit-distance">Edit Distance</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Problem Link</strong></td><td><strong>Articles</strong></td><td><strong>Solutions</strong></td></tr>
</thead>
<tbody>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/edit-distance/description/">Edit Distance</a></td><td></td><td><a target="_blank" href="https://github.com/subhakundu/DsAlgoPractice/blob/main/DynamicProgramming/EditDistance/PlainEditDistance/Solution.java">Github</a></td></tr>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/delete-operation-for-two-strings/description/">Delete Operations for two strings</a></td><td></td><td><a target="_blank" href="https://github.com/subhakundu/DsAlgoPractice/blob/main/DynamicProgramming/EditDistance/DeleteOperationsForTwoStrings/Solution.java">Github</a></td></tr>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/minimum-ascii-delete-sum-for-two-strings/description/">Minimum ASCII delete sum for two strings</a></td><td></td><td><a target="_blank" href="https://github.com/subhakundu/DsAlgoPractice/blob/main/DynamicProgramming/EditDistance/MinimumAsciiDeleteSum/Solution.java">Github</a></td></tr>
</tbody>
</table>
</div><h2 id="heading-longest-common-subsequence">Longest Common Subsequence</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Problem Link</strong></td><td><strong>Articles</strong></td><td><strong>Solutions</strong></td></tr>
</thead>
<tbody>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/longest-common-subsequence/description/">Longest Common Subsequence</a></td><td></td><td><a target="_blank" href="https://github.com/subhakundu/DsAlgoPractice/blob/main/DynamicProgramming/LongestCommonSubsequence/LCS/Solution.java">Github</a></td></tr>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/delete-operation-for-two-strings/description/">Delete Operations for Two Strings</a></td><td></td><td><a target="_blank" href="https://github.com/subhakundu/DsAlgoPractice/blob/main/DynamicProgramming/EditDistance/DeleteOperationsForTwoStrings/Solution.java">Github</a></td></tr>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/shortest-common-supersequence/description/">Shortest Common Subsequence</a></td><td></td><td><a target="_blank" href="https://github.com/subhakundu/DsAlgoPractice/tree/main/DynamicProgramming/LongestCommonSubsequence/ShortestCommonSuperSequence">Github</a></td></tr>
</tbody>
</table>
</div><h2 id="heading-longest-increasing-subsequence">Longest Increasing Subsequence</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Problem Link</strong></td><td><strong>Articles</strong></td><td><strong>Solutions</strong></td></tr>
</thead>
<tbody>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/longest-increasing-subsequence/description/">Longest Increasing Subsequence</a></td><td></td><td><a target="_blank" href="https://github.com/subhakundu/DsAlgoPractice/blob/main/DynamicProgramming/LongestIncreasingSubsequence/LIS/Solution.java">Github</a>, <a target="_blank" href="https://github.com/subhakundu/DsAlgoPractice/blob/main/DynamicProgramming/LongestIncreasingSubsequence/LIS/BinarySearch/Solution.java">Binary Search</a></td></tr>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/number-of-longest-increasing-subsequence/description/">Number of LIS</a></td><td></td><td><a target="_blank" href="https://github.com/subhakundu/DsAlgoPractice/blob/main/DynamicProgramming/LongestIncreasingSubsequence/CountOfLIS/Solution.java">Github</a></td></tr>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/russian-doll-envelopes/description/">Russian Doll Envelopes</a></td><td></td><td><a target="_blank" href="https://github.com/subhakundu/DsAlgoPractice/blob/main/DynamicProgramming/LongestIncreasingSubsequence/RussianDolls/Solution.java">Github</a></td></tr>
</tbody>
</table>
</div>]]></content:encoded></item><item><title><![CDATA[Backtracking: Generating Permutations]]></title><description><![CDATA[Problem Link
Summary
Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.
Test cases:
Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

Input: nums = [0...]]></description><link>https://blog.thecuriouscoder.in/backtracking-generating-permutations</link><guid isPermaLink="true">https://blog.thecuriouscoder.in/backtracking-generating-permutations</guid><category><![CDATA[backtracking]]></category><category><![CDATA[permutations]]></category><dc:creator><![CDATA[Subhasish Kundu]]></dc:creator><pubDate>Sat, 26 Jul 2025 10:26:13 GMT</pubDate><content:encoded><![CDATA[<p><a target="_blank" href="https://leetcode.com/problems/permutations/description/">Problem Link</a></p>
<h2 id="heading-summary">Summary</h2>
<p>Given an array <code>nums</code> of distinct integers, return all the possible permutations. You can return the answer in <strong>any order</strong>.</p>
<p><strong>Test cases:</strong></p>
<pre><code class="lang-plaintext">Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

Input: nums = [0,1]
Output: [[0,1],[1,0]]

Input: nums = [1]
Output: [[1]]

Input: nums = []
Output: []
</code></pre>
<h2 id="heading-algorithm">Algorithm</h2>
<p>Please refer to the <a target="_blank" href="https://github.com/subhakundu/DsAlgoPractice/blob/main/Backtracking/Permutations.java">Solution Link on Github</a>.</p>
<p>It is one of the most basic problems in <strong>backtracking</strong>. Let’s assume that there are n elements. Total number of permutations is <em>n!</em>. The crux of the problem is that, we have place given n numbers in n different positions. Let’s assume, we are constructing one permutation and we have placed k elements in first k positions. We have to place rest of the n-k elements at the n-k positions. For that, we can do</p>
<ol>
<li><p>We place (k+1)th element at (k+1)th position in an ongoing permutation.</p>
</li>
<li><p>Given we have to write a single threaded application, we would start processing (n-k-1) elements as next step. This requires recursion.</p>
</li>
</ol>
<p>We need to end the recursion. Otherwise, it would lead to Stack overflow. We would stop it when number of elements in the ongoing permutation equals to <strong>the total number of elements.</strong></p>
<h3 id="heading-why-it-is-a-backtracking-problem">Why it is a backtracking problem?</h3>
<p>Because, after we finish constructing a permutation, we have to construct next permutation. Let’s assume, we have constructed one permutation. A is placed at position k, and B is placed at position k+1. In next permutation, B will be placed at k, and A will be placed at k+1. Hence, we need to remove A from k, and then add B at k. To accomplish this, we require backtracking.</p>
<h3 id="heading-will-we-not-generate-same-permutation-repeatedly-if-we-keep-on-iterating-over-the-elements">Will we not generate same permutation repeatedly, if we keep on iterating over the elements?</h3>
<p>Valid question. The answer is no, because</p>
<ol>
<li><p>We are tracking if a number already exists or not (<a target="_blank" href="https://github.com/subhakundu/DsAlgoPractice/blob/main/Backtracking/Permutations.java#L18">code</a>). Hence, we will not place the same element again.</p>
</li>
<li><p>We will always end the recursion when number of elements in the permutation is equal to number of given elements.</p>
</li>
<li><p>The loop in <a target="_blank" href="https://github.com/subhakundu/DsAlgoPractice/blob/main/Backtracking/Permutations.java#L17">code</a> will always traverse n number times and it would not repeat.</p>
</li>
</ol>
<p>Yes, missing amny of this, would lead to infinite recursion.</p>
<h2 id="heading-complexities">Complexities</h2>
<h3 id="heading-time-complexities">Time Complexities</h3>
<p>The time complexity of this problem will have two parts</p>
<ol>
<li><p><strong>How many permutations we have to generate?</strong> - <em>O(n!)</em></p>
</li>
<li><p><strong>How many times we have to recurse down for each permutation?</strong> - <em>O(n)</em></p>
</li>
</ol>
<p><strong>Total Complexity:</strong> <em>O(n.n!)</em></p>
<h2 id="heading-other-notes">Other Notes</h2>
<ol>
<li><p>Recursion is perfect for this kind of problems because one part of the problem is solved, we need to solve other part.</p>
</li>
<li><p>To improve run time, we can use multi threaded approach. We can spawn new threads for each level of recursion to increase parallel execution. However, it would mean spawing n! threads. That might be impractical. It would only reduce actual duration of the execution. The theoretical time complexity will remain same - <em>O(n.n!)</em>.</p>
</li>
<li><p>Probably, we can fork n thread for first couple of level of recursion. It would provide a good balance.</p>
</li>
</ol>
<p><em>Please visit this</em> <a target="_blank" href="https://blog.thecuriouscoder.in/common-data-structures-and-algorithms-patterns"><em>page</em></a> <em>to see the problems I have solved and my analysis.</em></p>
]]></content:encoded></item><item><title><![CDATA[My Notes on Technical Papers]]></title><description><![CDATA[PaperNotes



Kafka]]></description><link>https://blog.thecuriouscoder.in/my-notes-on-technical-papers</link><guid isPermaLink="true">https://blog.thecuriouscoder.in/my-notes-on-technical-papers</guid><category><![CDATA[papers]]></category><dc:creator><![CDATA[Subhasish Kundu]]></dc:creator><pubDate>Sat, 26 Jul 2025 07:50:47 GMT</pubDate><content:encoded><![CDATA[<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Paper</strong></td><td><strong>Notes</strong></td></tr>
</thead>
<tbody>
<tr>
<td><a target="_blank" href="https://github.com/subhakundu/TechnicalPapers/blob/main/Kafka.pdf">Kafka</a></td><td></td></tr>
</tbody>
</table>
</div>]]></content:encoded></item><item><title><![CDATA[Common Data Structures and Algorithms Patterns]]></title><description><![CDATA[Pattern 1: Fast and Slow Pointers




Problem LinkArticlesSolution



Linked List CycleGithub

Happy NumberGithub

Find the duplicate number


Pattern 2: Sliding Window




Problem LinkArticlesSolution



Maximum Average SubarrayGithub

Longest Subst...]]></description><link>https://blog.thecuriouscoder.in/common-data-structures-and-algorithms-patterns</link><guid isPermaLink="true">https://blog.thecuriouscoder.in/common-data-structures-and-algorithms-patterns</guid><category><![CDATA[DSA]]></category><category><![CDATA[algorithms]]></category><dc:creator><![CDATA[Subhasish Kundu]]></dc:creator><pubDate>Sat, 26 Jul 2025 07:10:27 GMT</pubDate><content:encoded><![CDATA[<h2 id="heading-pattern-1-fast-and-slow-pointers">Pattern 1: Fast and Slow Pointers</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Problem Link</strong></td><td><strong>Articles</strong></td><td><strong>Solution</strong></td></tr>
</thead>
<tbody>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/linked-list-cycle/description/">Linked List Cycle</a></td><td></td><td><a target="_blank" href="https://github.com/subhakundu/DsAlgoPractice/blob/main/FastAndSlowPointers/LinkedListCycle/Solution.java">Github</a></td></tr>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/happy-number/description/">Happy Number</a></td><td></td><td><a target="_blank" href="https://github.com/subhakundu/DsAlgoPractice/blob/main/FastAndSlowPointers/HappyNumber/Solution.java">Github</a></td></tr>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/find-the-duplicate-number/description/">Find the duplicate number</a></td><td></td></tr>
</tbody>
</table>
</div><h2 id="heading-pattern-2-sliding-window">Pattern 2: Sliding Window</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Problem Link</strong></td><td><strong>Articles</strong></td><td><strong>Solution</strong></td></tr>
</thead>
<tbody>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/maximum-average-subarray-i/description/">Maximum Average Subarray</a></td><td></td><td><a target="_blank" href="https://github.com/subhakundu/DsAlgoPractice/blob/main/SlidingWindow/MaximumAverageSubarray/Solution.java">Github</a></td></tr>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/longest-substring-without-repeating-characters/description/">Longest Substring Without Repeating Character</a></td><td></td><td><a target="_blank" href="https://github.com/subhakundu/DsAlgoPractice/blob/main/SlidingWindow/LongestSubstringWithoutRepeatingCharacters/Solution.java">Github</a></td></tr>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/minimum-window-substring/description/">Minimum window substring</a></td><td></td><td><a target="_blank" href="https://github.com/subhakundu/DsAlgoPractice/blob/main/SlidingWindow/MinimumWindowSubstring/Solution.java">Github</a></td></tr>
</tbody>
</table>
</div><h2 id="heading-pattern-3-merge-intervalsoverlapping-intervals">Pattern 3: Merge Intervals/Overlapping Intervals</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Problem Link</strong></td><td><strong>Articles</strong></td><td><strong>Solution</strong></td></tr>
</thead>
<tbody>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/merge-intervals/description/">Merge Intervals</a></td><td></td><td><a target="_blank" href="https://github.com/subhakundu/DsAlgoPractice/blob/main/MergedIntervals/MergeIntervals/Solution.java">Github</a></td></tr>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/insert-interval/description/">Insert Intervals</a></td><td></td><td><a target="_blank" href="https://github.com/subhakundu/DsAlgoPractice/blob/main/MergedIntervals/InsertIntervals/LinearSearch/Solution.java">Linear Search</a>, <a target="_blank" href="https://github.com/subhakundu/DsAlgoPractice/blob/main/MergedIntervals/InsertIntervals/BinarySearch/Solution.java">Binary Search</a></td></tr>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/non-overlapping-intervals/description/">Non-overlapping Intervals</a></td><td></td></tr>
</tbody>
</table>
</div><h2 id="heading-pattern-4-linkedlist-in-place-reversal">Pattern 4: <strong>LinkedList In-place Reversal</strong></h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Problem Link</strong></td><td><strong>Articles</strong></td><td><strong>Solution</strong></td></tr>
</thead>
<tbody>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/reverse-linked-list/description/">Reverse Linked List</a></td><td></td><td><a target="_blank" href="https://github.com/subhakundu/DsAlgoPractice/blob/main/LinkedListInPlaceReversal/Iterative/Solution.java">Iterative</a>, <a target="_blank" href="https://github.com/subhakundu/DsAlgoPractice/blob/main/LinkedListInPlaceReversal/Recursive/Solution.java">Recursive</a></td></tr>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/reverse-linked-list-ii/description/">Reverse Linked List II</a></td><td></td><td></td></tr>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/swap-nodes-in-pairs/description/">Swap Nodes in Pairs</a></td><td></td></tr>
</tbody>
</table>
</div><h2 id="heading-pattern-5-prefix-sum">Pattern 5: Prefix Sum</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Problem Link</strong></td><td><strong>Articles</strong></td><td><strong>Solution</strong></td></tr>
</thead>
<tbody>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/range-sum-query-immutable/description/">Range Sum Query - Immutable</a></td><td></td><td><a target="_blank" href="https://github.com/subhakundu/DsAlgoPractice/blob/main/PrefixSum/RangeSumQuery.java">Github</a></td></tr>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/contiguous-array/description/">Contiguous Array</a></td><td></td><td><a target="_blank" href="https://github.com/subhakundu/DsAlgoPractice/blob/main/PrefixSum/ContiguousArray.java">Github</a></td></tr>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/subarray-sum-equals-k/description/">Subarray Sum Equals K</a></td><td></td><td><a target="_blank" href="https://github.com/subhakundu/DsAlgoPractice/tree/main/PrefixSum/SubarraySumEqualsK">Github</a></td></tr>
</tbody>
</table>
</div><h2 id="heading-pattern-6-top-k-elements">Pattern 6: <strong>Top ‘K’ Elements</strong></h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Problem Link</strong></td><td><strong>Articles</strong></td><td><strong>Solution</strong></td></tr>
</thead>
<tbody>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/kth-largest-element-in-an-array/description/">Kth Largest Element in an Array</a></td><td></td><td><a target="_blank" href="https://github.com/subhakundu/DsAlgoPractice/blob/main/Heap/KthLargetElementInAnArray.java">Github</a></td></tr>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/top-k-frequent-elements/description/">Top K Frequent Elements</a></td><td></td><td><a target="_blank" href="https://github.com/subhakundu/DsAlgoPractice/blob/main/Heap/TopKFrequentElements.java">Github</a></td></tr>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/find-k-pairs-with-smallest-sums/description/">Find K Pairs with Smallest Sums</a></td><td></td><td><a target="_blank" href="https://github.com/subhakundu/DsAlgoPractice/blob/main/Heap/FindKPairsWithSmallestSum.java">Github</a></td></tr>
</tbody>
</table>
</div><h2 id="heading-pattern-7-binary-search">Pattern 7: Binary Search</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Problem Link</strong></td><td><strong>Articles</strong></td><td><strong>Solution</strong></td></tr>
</thead>
<tbody>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/search-in-rotated-sorted-array/description/">Search in a rotated sorted array</a></td><td></td><td><a target="_blank" href="https://github.com/subhakundu/DsAlgoPractice/tree/main/BinarySearch/FindingElementInRotatedArray">Github</a></td></tr>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/description/">Find Minimum in a rotated sorted array</a></td><td></td><td><a target="_blank" href="https://github.com/subhakundu/DsAlgoPractice/blob/main/BinarySearch/FindMinimumInRotatedSortedArray.java">Github</a></td></tr>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/search-a-2d-matrix-ii/description/">Search a 2D matrix II</a></td><td></td><td><a target="_blank" href="https://github.com/subhakundu/DsAlgoPractice/tree/main/BinarySearch/SearchInA2DMatrix">Github</a></td></tr>
</tbody>
</table>
</div><h2 id="heading-pattern-8-binary-tree-traversal">Pattern 8: Binary Tree Traversal</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Problem Link</strong></td><td><strong>Articles</strong></td><td><strong>Solution</strong></td></tr>
</thead>
<tbody>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/binary-tree-paths/description/">Binary Tree Paths</a></td><td></td><td><a target="_blank" href="https://github.com/subhakundu/DsAlgoPractice/blob/main/BinaryTreeTraversal/BinaryTreePaths.java">Github</a></td></tr>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/kth-smallest-element-in-a-bst/description/">K-th Smallest Element in BST</a></td><td></td><td><a target="_blank" href="https://github.com/subhakundu/DsAlgoPractice/blob/main/BinaryTreeTraversal/KthSmallestElement/Recursive/Solution.java">Recursive</a>, <a target="_blank" href="https://github.com/subhakundu/DsAlgoPractice/blob/main/BinaryTreeTraversal/KthSmallestElement/Iterative/Solution.java">Iterative</a></td></tr>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/binary-tree-maximum-path-sum/description/">Binary Tree Maximum Path Sum</a></td><td></td><td></td></tr>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/binary-tree-inorder-traversal/description/">Inorder Traversal</a></td><td></td><td><a target="_blank" href="https://github.com/subhakundu/DsAlgoPractice/tree/main/Tree/InorderTraversal">Github</a></td></tr>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/symmetric-tree/description/">Symmetric Tree</a></td><td></td><td><a target="_blank" href="https://github.com/subhakundu/DsAlgoPractice/blob/main/Tree/SymmetricTree/Solution.java">Github</a></td></tr>
</tbody>
</table>
</div><h2 id="heading-pattern-9-depth-first-search">Pattern 9: Depth First Search</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Problem Link</strong></td><td><strong>Articles</strong></td><td><strong>Solution</strong></td></tr>
</thead>
<tbody>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/clone-graph/description/">Clone Graph</a></td><td></td><td><a target="_blank" href="https://github.com/subhakundu/DsAlgoPractice/blob/main/Graph/ClonedGraph/DFS.java">Github</a></td></tr>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/path-sum-ii/description/">Path Sum II</a></td><td></td><td><a target="_blank" href="https://github.com/subhakundu/DsAlgoPractice/blob/main/Tree/PathSum2/Solution.java">Github</a></td></tr>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/course-schedule-ii/description/">Course Schedule II</a></td><td></td><td></td></tr>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/same-tree/description/">Same Tree</a></td><td></td><td><a target="_blank" href="https://github.com/subhakundu/DsAlgoPractice/blob/main/DepthFirstSearch/SameTree/Solution.java">Github</a></td></tr>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/number-of-provinces/">Number of Provinces</a></td><td></td><td><a target="_blank" href="https://github.com/subhakundu/DsAlgoPractice/blob/main/Graph/NumberOfProvinces/Solution.java">Github</a> (DFS)</td></tr>
</tbody>
</table>
</div><h2 id="heading-pattern-10-breadth-first-search">Pattern 10: Breadth First Search</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Problem Link</strong></td><td><strong>Articles</strong></td><td><strong>Solution</strong></td></tr>
</thead>
<tbody>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/binary-tree-level-order-traversal/description/">Level Order Traversal</a></td><td></td><td><a target="_blank" href="https://github.com/subhakundu/DsAlgoPractice/blob/main/BreadthFirstSearch/BinaryTreeLevelOrderTraversal.java">GitHub</a></td></tr>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/rotting-oranges/description/">Rotting Oranges</a></td><td></td><td><a target="_blank" href="https://github.com/subhakundu/DsAlgoPractice/blob/main/Graph/RottenOranges/Solution.java">Github</a></td></tr>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/word-ladder/description/">Word Ladder</a></td><td></td><td></td></tr>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/clone-graph/description/">Clone Graph</a></td><td></td><td><a target="_blank" href="https://github.com/subhakundu/DsAlgoPractice/blob/main/Graph/ClonedGraph/BFS.java">Github</a></td></tr>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/find-if-path-exists-in-graph/description/">If Path Exists</a></td><td></td><td><a target="_blank" href="https://github.com/subhakundu/DsAlgoPractice/blob/main/Graph/PathFinding/IfPathExists/BFS/Solution.java">BFS</a>, <a target="_blank" href="https://github.com/subhakundu/DsAlgoPractice/blob/main/Graph/PathFinding/IfPathExists/UnionFind/Solution.java">Union Find</a></td></tr>
</tbody>
</table>
</div><h2 id="heading-pattern-11-matrix-traversal">Pattern 11: <strong>Matrix Traversal</strong></h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Problem Link</strong></td><td><strong>Articles</strong></td><td><strong>Solution</strong></td></tr>
</thead>
<tbody>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/flood-fill/description/">Flood Fill</a></td><td></td><td><a target="_blank" href="https://github.com/subhakundu/DsAlgoPractice/blob/main/Graph/Matrix/FloodFill/Solution.java">Github</a></td></tr>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/number-of-islands/description/">Number of Islands</a></td><td></td><td><a target="_blank" href="https://github.com/subhakundu/DsAlgoPractice/blob/main/Graph/Matrix/NumberOfIslands/Solution.java">Github</a></td></tr>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/surrounded-regions/description/">Surrounded Regions</a></td><td></td><td><a target="_blank" href="https://github.com/subhakundu/DsAlgoPractice/blob/main/Graph/Matrix/SurroundedRegions/Solution.java">Github</a></td></tr>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/number-of-closed-islands/description/">Number of Closed Islands</a></td><td></td><td><a target="_blank" href="https://github.com/subhakundu/DsAlgoPractice/tree/main/Graph/Matrix/NumberOfClosedIslands/WithoutGlobalVariable">Without global variable</a>, <a target="_blank" href="https://github.com/subhakundu/DsAlgoPractice/tree/main/Graph/Matrix/NumberOfClosedIslands/WithGlobalVariable">with global variable</a> (cleaner, but not best practice)</td></tr>
</tbody>
</table>
</div><h2 id="heading-pattern-12-backtracking">Pattern 12: Backtracking</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Problem Link</strong></td><td><strong>Articles</strong></td><td><strong>Solution</strong></td></tr>
</thead>
<tbody>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/permutations/description/">Permutations</a></td><td><a target="_blank" href="https://blog.thecuriouscoder.in/backtracking-generating-permutations">Notes</a></td><td><a target="_blank" href="https://github.com/subhakundu/DsAlgoPractice/blob/main/Backtracking/Permutations.java">Github</a></td></tr>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/subsets/description/">Subsets</a></td><td></td><td><a target="_blank" href="https://github.com/subhakundu/DsAlgoPractice/blob/main/Backtracking/Subsets.java">Github</a></td></tr>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/n-queens/description/">N-queens</a></td><td></td></tr>
</tbody>
</table>
</div><h2 id="heading-pattern-13-monotonic-stack">Pattern 13: Monotonic Stack</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Problem Link</strong></td><td><strong>Articles</strong></td><td><strong>Solution</strong></td></tr>
</thead>
<tbody>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/next-greater-element-i/description/">Next Greater Element I</a></td><td></td><td><a target="_blank" href="https://github.com/subhakundu/DsAlgoPractice/blob/main/MonotonicStack/NextGreaterElementI/Solution.java">Github</a></td></tr>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/daily-temperatures/description/">Daily Temperatures</a></td><td></td><td></td></tr>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/largest-rectangle-in-histogram/description/">Largest Rectangle in Histogram</a></td><td></td></tr>
</tbody>
</table>
</div><h2 id="heading-pattern-14-generic-graphs">Pattern 14: Generic Graphs</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Problem Link</strong></td><td><strong>Articles</strong></td><td><strong>Solution</strong></td></tr>
</thead>
<tbody>
<tr>
<td><a target="_blank" href="https://leetcode.com/problems/minimum-number-of-vertices-to-reach-all-nodes/description/">Minimum Number of Vertices to Reach All Nodes</a></td><td></td><td><a target="_blank" href="https://github.com/subhakundu/DsAlgoPractice/blob/main/Graph/MinimumNumberOfVertices/Solution.java">Solution</a></td></tr>
<tr>
<td></td><td></td><td></td></tr>
</tbody>
</table>
</div>]]></content:encoded></item><item><title><![CDATA[OSS Contributions: 16th-23rd August 2021]]></title><description><![CDATA[After a long time, I started contributing to open-source software. For a long time, I had my eye on  Deno. This week, I merged my first PR in Deno Lint. Following is the detailed post about the issue.
Issue 425

Category: Refactoring
Description of t...]]></description><link>https://blog.thecuriouscoder.in/oss-contributions-16th-23rd-august-2021</link><guid isPermaLink="true">https://blog.thecuriouscoder.in/oss-contributions-16th-23rd-august-2021</guid><category><![CDATA[Open Source]]></category><category><![CDATA[opensource]]></category><category><![CDATA[coding]]></category><category><![CDATA[programmer]]></category><category><![CDATA[programing]]></category><dc:creator><![CDATA[Subhasish Kundu]]></dc:creator><pubDate>Sun, 22 Aug 2021 16:48:31 GMT</pubDate><content:encoded><![CDATA[<p>After a long time, I started contributing to open-source software. For a long time, I had my eye on  <a target="_blank" href="https://deno.land/">Deno</a>. This week, I merged my first PR in <a target="_blank" href="https://github.com/denoland/deno_lint">Deno Lint</a>. Following is the detailed post about the issue.</p>
<h2 id="issue-425httpsgithubcomdenolanddenolintissues425">Issue <a target="_blank" href="https://github.com/denoland/deno_lint/issues/425">425</a></h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1629650692526/tEeRz2p1U.jpeg" alt="deno.jpeg" /></p>
<p><strong>Category:</strong> Refactoring</p>
<h3 id="description-of-the-issue">Description of the Issue</h3>
<p>If we go through the issue, we could see that in the tests of each rule, there is a repeat of messages and hints. For example, from *\ban_ts_comments.rs from a <a target="_blank" href="https://github.com/denoland/deno_lint/blob/a15d25bb84d0067971eaf3c530548b50556e35ad/src/rules/ban_ts_comment.rs#[L252,L260]">previous commit</a>, we can see that messages and hints are being repeated</p>
<pre><code>    r<span class="hljs-comment">#"// <span class="hljs-doctag">@ts</span>-nocheck"#: [</span>
            {
              <span class="hljs-symbol">col:</span> <span class="hljs-number">0</span>,
              <span class="hljs-symbol">message:</span> DirectiveKind::Nocheck.as_message(),
              <span class="hljs-symbol">hint:</span> DirectiveKind::Nocheck.as_hint(),
            }
          ],
    r<span class="hljs-comment">#"/// <span class="hljs-doctag">@ts</span>-nocheck"#: [</span>
            {
              <span class="hljs-symbol">col:</span> <span class="hljs-number">0</span>,
              <span class="hljs-symbol">message:</span> DirectiveKind::Nocheck.as_message(),
              <span class="hljs-symbol">hint:</span> DirectiveKind::Nocheck.as_hint(),
            }
          ],
    r<span class="hljs-comment">#"//<span class="hljs-doctag">@ts</span>-nocheck"#: [</span>
            {
              <span class="hljs-symbol">col:</span> <span class="hljs-number">0</span>,
              <span class="hljs-symbol">message:</span> DirectiveKind::Nocheck.as_message(),
              <span class="hljs-symbol">hint:</span> DirectiveKind::Nocheck.as_hint(),
            }
          ],
    r<span class="hljs-comment">#"// <span class="hljs-doctag">@ts</span>-nocheck    "#: [</span>
      {
        <span class="hljs-symbol">col:</span> <span class="hljs-number">0</span>,
        <span class="hljs-symbol">message:</span> DirectiveKind::Nocheck.as_message(),
        <span class="hljs-symbol">hint:</span> DirectiveKind::Nocheck.as_hint(),
      }
</code></pre><p>The test cases for each rule in Deno Lint could be grouped together based on common messages and hints. This issue talks about that. Macro <a target="_blank" href="https://github.com/denoland/deno_lint/blob/a15d25bb84d0067971eaf3c530548b50556e35ad/src/test_util.rs#L37">assert_lint_err</a> is responsible for running test cases. </p>
<h3 id="solution">Solution</h3>
<p>In this <a target="_blank" href="https://github.com/denoland/deno_lint/commit/576f5a1fc725a49aa86ea5be0ae061ffaaed6bcf">commit</a>, I have extended this macro with new rules, where we could use it to run multiple test cases with the same messages and hints. Following is the modified <a target="_blank" href="https://github.com/denoland/deno_lint/blob/main/src/test_util.rs#[L65,L97]">assert_lint_err</a> macro. I have added two new rules, where we could group tests based on messages and hints.</p>
<h3 id="challenges">Challenges</h3>
<ol>
<li>I did not know about Rust. I had to learn about <a target="_blank" href="https://doc.rust-lang.org/rust-by-example/macros.html">macro_rules!</a> to solve this issue. I have gotten interested in it. Let me see, how much I make progress.</li>
<li>As this is the first time, I was contributing to Deno, I was not aware of all the formalities. <a target="_blank" href="https://github.com/magurotuna">Yusuke Tanaka</a> from the Deno team helped me a lot. They have been very receptive and active. Their help has encouraged me to take up my <a target="_blank" href="https://github.com/denoland/deno_lint/issues/779">new issue</a> as well.</li>
<li>This is not a challenge, but learning. I could not totally comprehend Rust-style styling. The reviewer pointed those out to me. From next time onwards, I have to be better with that.</li>
</ol>
<h3 id="follow-up">Follow up</h3>
<p>In this commit, I have covered  <a target="_blank" href="https://github.com/denoland/deno_lint/blob/main/src/rules/ban_ts_comment.rs">ban_ts_comment.rs</a>  and 
  <a target="_blank" href="https://github.com/denoland/deno_lint/blob/main/src/rules/no_await_in_loop.rs">no_await_in_loop.rs</a>. I need to cover other files as well. If someone reads this post and feels good to contribute, I would encourage them to do that 😀😀. Connect with me or anyone in Deno team for help/any questions. We will be happy to help.</p>
<p>I will write a detailed post on various aspects of Deno and Deno development and contributions in subsequent blog posts.</p>
]]></content:encoded></item><item><title><![CDATA[Best Practices of Exception Handling]]></title><description><![CDATA[Exception handling is one of the most important aspects of software engineering. There are many articles on this topic. Yet, I have seen other developers and myself making mistakes and not exiting gracefully. In my experience, I have encountered many...]]></description><link>https://blog.thecuriouscoder.in/best-practices-of-exception-handling</link><guid isPermaLink="true">https://blog.thecuriouscoder.in/best-practices-of-exception-handling</guid><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Programming Tips]]></category><category><![CDATA[Java]]></category><category><![CDATA[programmer]]></category><category><![CDATA[coding]]></category><dc:creator><![CDATA[Subhasish Kundu]]></dc:creator><pubDate>Sat, 17 Jul 2021 06:06:29 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1626500263959/7GuQz5SqN.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Exception handling is one of the most important aspects of software engineering. There are many articles on this topic. Yet, I have seen other developers and myself making mistakes and not exiting gracefully. In my experience, I have encountered many exceptional scenarios and failure reports. I have written a lot of codes and made mistakes a thousand times. The following quote by Malcolm Muggeridge summarises exception handling pretty well.</p>
<blockquote>
<p>Few men of action have been able to make a graceful exit at the appropriate time.</p>
</blockquote>
<p>In this article, I am documenting my share of learnings along the process.</p>
<p>Note: I am using Java in this article as a reference. It is my primary language of coding. But, the principles are language agnostic. I will cover the things that are out of the scope of coding as well. As I learn new things about the topic, I will keep this post updated. I have used <em>unchecked</em> and <em>runtime exceptions</em> interchangeably.</p>
<p>I am dividing this article into two sections</p>
<ol>
<li>Handling exceptions inside code</li>
<li>Handling exceptions outside code</li>
</ol>
<h2 id="handling-exceptions-inside-code">Handling exceptions inside code</h2>
<h3 id="1-use-exceptions-for-exceptional-scenarios">1. Use Exceptions for Exceptional Scenarios</h3>
<p>Exceptions should be used for exceptional scenarios only. In  <a target="_blank" href="https://www.oreilly.com/library/view/effective-java/9780134686097/">Effective Java</a>, author  <a target="_blank" href="https://en.wikipedia.org/wiki/Joshua_Bloch">Joshua Bloch</a> is extremely vocal about this. If he is so vocal about this, it is an issue. I hope none of us do this anymore. Following is an example from the book</p>
<pre><code><span class="hljs-comment">// Horrible abuse of exceptions. Don't ever do this!</span>
<span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>;
    <span class="hljs-keyword">while</span>(<span class="hljs-literal">true</span>)
        range[i++].climb();
} <span class="hljs-keyword">catch</span> (ArrayIndexOutOfBoundsException e) {
}
</code></pre><p>Try to guess the answer! The above code is clever but lacks readability, intent, and performance. JVM does not apply some optimization as well seeing try-catch.</p>
<p>The simpler version is readable, understandable, and lets JVM apply optimizations.</p>
<pre><code><span class="hljs-selector-tag">for</span> (Mountain <span class="hljs-attribute">m </span>: range)
    <span class="hljs-selector-tag">m</span><span class="hljs-selector-class">.climb</span>();
</code></pre><h3 id="2-never-ignore-exceptions-in-code">2. Never Ignore Exceptions in Code</h3>
<p>It is obvious but often forgotten. I have seen a similar code as follows.</p>
<pre><code><span class="hljs-selector-tag">try</span> {
     <span class="hljs-selector-tag">executeCommand</span>();
} <span class="hljs-selector-tag">catch</span> (IllegalStateException e) {
    <span class="hljs-comment">//Highly suspicious. Anything can happen here</span>
    <span class="hljs-comment">//without your knowledge.</span>
}
</code></pre><p>This is not a good practice at all. In the future, if something happens, you will never know. I am also a criminal of ignoring an exception altogether (by mistake) 😔. Later I fixed it while refactoring. I still don't know about the impact 🥶. And it still bugs me!</p>
<h3 id="3-make-exceptions-visible-when-occurs">3. Make Exceptions Visible When Occurs</h3>
<p>Make sure you have ways to know that exception has occurred. It might be some metrics or UI-based log aggregator for capturing all logs. But it is a necessity. Otherwise, you will not know if there is anything wrong with the system.</p>
<h3 id="4-dont-use-log-and-then-throw-exception-strategy">4. Don't Use "Log and Then Throw" Exception Strategy</h3>
<p>If you log and throw another exception, the catcher of exceptions might again log details about exceptions. So, you will have redundant information for the same exception. It will pollute error logs. In turn, it will make your life uneasy while debugging.</p>
<pre><code><span class="hljs-keyword">try</span> {
      executeCommand();
} <span class="hljs-keyword">catch</span> (IllegalStateException e) {
      <span class="hljs-comment">// Following log is redundant information.</span>
      <span class="hljs-comment">// It will pollute your error log.</span>
      <span class="hljs-built_in">log</span>.error(<span class="hljs-string">"Exception at doSomething:"</span>, e); 
      <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> BadRequest(<span class="hljs-string">"Exception has occurred."</span>, e);
}
</code></pre><h3 id="5-log-errors-with-exception-details">5. Log Errors with Exception Details</h3>
<p>This is a common practice. Let me warn you! If you are not logging exception details, you are digging a hole for the future. It will be hard to debug an actual issue. Your on-call will keep looking for issues without knowing where to look. Having a proper stack trace will help him to decide where to look. It will help root cause the issue faster.</p>
<h3 id="6-use-exception-translator">6. Use Exception Translator</h3>
<p>Dependencies or library calls throw exceptions. Those exceptions can be specific to the callee. Those are seldom related to the caller. But we need to handle exceptions at the caller end. It is better to map specific exceptions from the callee to exception types of the caller. Exception Translator is one of the best tools available in this case. Another way can be propagating status codes such as success or failure, of the operation. In the following example, CommandArgumentException conveys better meaning relative to the caller.</p>
<pre><code><span class="hljs-keyword">try</span> {
      executeCommand();
} <span class="hljs-keyword">catch</span> (IllegalStateException e) {
      <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> CommandArgumentException(<span class="hljs-string">"Arguments 
             to command are not right."</span>, e);
}
</code></pre><p>Also, I have worked on monolith software written in C (codebase size was 2.2GB). In C, we don't have a proper exception handling framework like in Java. In such cases, exception translator and framework help a lot. Following are a couple of ways</p>
<ol>
<li>It simplifies the handling of exceptions by calling call-back functions. In case of some null pointer exception, you should hand over the control to the exception handler. You cannot call exit(). For debugging, you need to collect reports.</li>
<li>If you don't capture stack trace in Exception Handler, you will not be able to debug the issue. The stack trace will help you create the test case. It will be your friend for the entire debugging.</li>
</ol>
<h3 id="7-be-skeptical-about-runtime-exception">7. Be skeptical about Runtime Exception</h3>
<p>Compilers force us to try-catch checked exceptions. We often miss runtime exceptions. We should be skeptical about runtime exceptions especially while calling dependencies. In large-scale distributed systems, failure is common. We once encountered a dependency call that does not have any checked exceptions. After careful inspection, we wrapped it up inside try-catch for runtime exceptions. It allowed us to exit gracefully.</p>
<h3 id="8-consider-catching-generic-exception">8. Consider catching Generic Exception</h3>
<p>As I work in distributed system development, I generally follow this. It helps to exit with grace. But I make sure to log this and capture such exceptions. In case of a surge of generic exceptions, we should investigate the issue. There might be some new checked exception in the callee side or there is some runtime exception. In any case, we should check the issue.</p>
<h3 id="9-dont-catch-throwables">9. Don't catch Throwables</h3>
<p>Throwables are the superclass of everything including Errors. Errors are used by JVM to indicate a serious system-related problem like StackOverflowError etc. Applications are not supposed to handle these errors. When JVM throws an error, there is some problem. Go check it! 🧐</p>
<h3 id="10-strive-for-failure-atomicity">10. Strive for Failure Atomicity</h3>
<p>This one is interesting. Let me elaborate on failure atomicity. In case of a failed operation on an object, we should roll back all the changes to the previous state. The object should not have partial updates. So, we can check if an operation can fail or not. We can use a checker function for this. JDK has some good examples of this. Iterator interface in Java has a checker hasNext() method. If it fails, we generally don't call the next() method. We can use this pattern as well when needed.</p>
<h3 id="11-document-all-exceptions">11. Document All Exceptions</h3>
<p>Most of the developers dislike documentation. As we write a piece code, we leave our legacy. Your documentation ensures your successor understands your code. Secretly, we all hope - when the next developer sees our code, he says </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1626501053543/sxoZWV83v.jpeg" alt="itsgood.jpeg" /></p>
<p>We should document all the exceptions including runtime exceptions. In Java, the "throws" clause forces to check checked exceptions. For covering all the bases, we should document runtime exceptions as well.</p>
<ul>
<li>We should document all exceptions including checked and unchecked using the JavaDoc '@throws' tag. Don't just mention Exception or Throwable. The below example does not express anything.<pre><code><span class="hljs-comment">/**
* JavaDoc Exception sample documentation
*  <span class="hljs-doctag">@throws</span> Exception in case of exceptional scenarios. 
*/</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">doSomething</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> AnException, AnotherException </span>{
  ...
}
</code></pre></li>
<li>We should only include checked exceptions in the throws clause, but not unchecked exceptions. It lets developers know that an exception mentioned in JavaDoc, but missing in the throws clause is <em>unchecked</em>.</li>
<li>Document the condition for which exception is thrown. For the above example, it is desirable to include conditions for which each exception is thrown.</li>
</ul>
<h3 id="12-always-cover-exceptions-in-unit-tests">12. Always cover Exceptions in Unit Tests</h3>
<p>This will give you confidence that your code works during exceptional scenarios. Check for outputs during exceptions. If it is not the same as you expected, anything can fail in production. </p>
<h3 id="13-add-your-counters-in-unit-tests">13. Add Your Counters in Unit Tests</h3>
<p>In case you use some counter or special logs during the exception, your unit tests for exceptions should cover those. Unit tests will fail in case someone changes counter or logs. And seldom, we have reasons to change these. If there is any reason, the developer should know why it was there in the first place. Your tests should be like documentation. It should cover all the aspects of your code including exceptional scenarios.</p>
<h2 id="handling-exceptions-outside-code">Handling exceptions outside code</h2>
<p>Operations are one of the big issues in large software systems. It includes a large-scale distributed system as well as a standalone desktop or mobile app. Sustenance of our service is one of the most important goals. We should have a proper mechanism for handling error scenarios. Following are my two cents on this</p>
<h3 id="1-indicators-and-logs-should-have-meaning">1. Indicators and Logs Should have Meaning</h3>
<p>Your on-call might have to debug a production issue at midnight. The last thing he wants at that time is confusion. Good logs and indicators (specific to your use case) can help him find the root cause of the issue faster. Ambiguity and complexity are hindrances to the root cause of the issue.</p>
<p>Now food for thought, we have two code segments.
<strong>Option 1</strong></p>
<pre><code>String serviceA = "Something has happened in serviceA";
String serviceB = "Something has happened in serviceB";
//somewhere <span class="hljs-keyword">else</span>
<span class="hljs-keyword">log</span>.error(serviceA);
//somewhere <span class="hljs-keyword">else</span>
<span class="hljs-keyword">log</span>.error(serviceB);
</code></pre><p><strong>Option 2</strong></p>
<pre><code><span class="hljs-keyword">String</span> errorStatement = <span class="hljs-string">"Something has happened in "</span>;
<span class="hljs-keyword">String</span> serviceA = <span class="hljs-string">"serviceA"</span>;
<span class="hljs-keyword">String</span> serviceB = <span class="hljs-string">"serviceB"</span>;
<span class="hljs-comment">//somewhere else</span>
log.<span class="hljs-built_in">error</span>(errorStatement + serviceA);
<span class="hljs-comment">//somewhere else</span>
log.<span class="hljs-built_in">error</span>(errorStatement + serviceB);
</code></pre><p>Suppose, we got an exception at midnight and we are getting "Something has happened in serviceA" as exception signature. Which one do you think will help to find code faster? I think Option 1. Single copy-pasting is easier than creating strings from multiple variables. Obviously, with the signature of exception, you can fast-track your problematic point. I still find Option 1 easier for on-call.</p>
<p>Note: Have you checked the last blank space at the end of <em>errorStatement</em> definition? These small spaces can give you nightmares.</p>
<h3 id="2-dont-ignore-metrics">2. Don't Ignore Metrics</h3>
<p>Add metrics wherever you think an error might occur. And add alarms on this. This will let you know if something is wrong with your system. In the monolith that I worked on, we incorporated  <a target="_blank" href="https://en.wikipedia.org/wiki/AddressSanitizer">AddressSantizer</a> to collect data about runtime exceptions. It was worth it. It helped a lot for finding a lot of long-term issues. I can still remember the days of debugging a problematic pointer! 😫</p>
<h3 id="3-plan-your-action">3. Plan Your Action</h3>
<p>Metrics and alarms without action items are meaningless. It is the same as a fire brigade team without protocol. Update the run-book with all relevant details and action items for important exceptions. Also, if required, add metrics to the dashboard.</p>
<h3 id="4-keep-your-counters-updated">4. Keep your Counters Updated</h3>
<p>You don't want a false alarm in the middle of the night. If you need to update an alarm, update it without delay. Getting regular wrong alarms can make you lose your trust in your system.</p>
<h2 id="generic-guidelines-for-handling-exception">Generic Guidelines for Handling Exception</h2>
<p>Here are some general guidelines for handling exceptions.</p>
<h3 id="1-always-be-skeptical">1. Always Be Skeptical</h3>
<p>Skepticism is better than optimism for handling errors and exceptions. Even if you have done everything, exceptions will occur.  If you have a proper mechanism in place, you can debug an issue faster.</p>
<h3 id="2-aim-for-sustenance">2. Aim for Sustenance</h3>
<p>If you build your system for sustenance, you will be better prepared for unknowns. This is one of the signs of mature developers.</p>
<h3 id="3-exceptions-are-not-your-mistake">3. Exceptions are not Your Mistake</h3>
<p>Failure is seldom a single developer's mistake. From coding a solution to deploying that involves a lot of steps. Any mistake at any stage can cause failure. We should aim for reducing failures by owning the process. There might be some issues unknown to the team. The developer and reviewers might miss it. Lack of testing might have missed the bug. We should look forward to improving the process. A root-cause analysis might help in this regard.</p>
<h2 id="conclusion">Conclusion</h2>
<p>Exception handling is a well-known misunderstood aspect of programming. In summary, we</p>
<ol>
<li>Should aim for sustenance and share knowledge across the way. It will help a lot.</li>
<li>Do not ignore exceptions. Handle it properly. Some principles mentioned might not be applicable to you. Break those and make yours. And share it with others.</li>
<li>Do not play blame games. It will not help anyone.</li>
</ol>
<p>We know how to use try-catch, but we don't know how it can affect our system. This article is my attempt to capture my thoughts on this topic. Please like the post if you enjoyed reading it. Let me know in the comments if you have any thoughts or questions.</p>
<p>Happy Learning!! 😀</p>
]]></content:encoded></item><item><title><![CDATA[JavaScript Event Loop]]></title><description><![CDATA[Sometime back, I started learning about JavaScript and React JS internals. My goal is to understand the internals of JavaScript and frameworks. In my last article, I wrote about  ReactJS internals. To understand more about React Fiber, we need to und...]]></description><link>https://blog.thecuriouscoder.in/javascript-event-loop</link><guid isPermaLink="true">https://blog.thecuriouscoder.in/javascript-event-loop</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[javascript framework]]></category><category><![CDATA[Event Loop]]></category><category><![CDATA[events]]></category><dc:creator><![CDATA[Subhasish Kundu]]></dc:creator><pubDate>Mon, 28 Jun 2021 03:51:51 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1624847447553/CODn8n5RK.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Sometime back, I started learning about JavaScript and React JS internals. My goal is to understand the internals of JavaScript and frameworks. In my last article, I wrote about  <a target="_blank" href="https://blog.thecuriouscoder.in/abstract-introduction-to-react-internals">ReactJS internals</a>. To understand more about React Fiber, we need to understand some preliminary JavaScript concept implementation. In the next three posts, I will be explaining in detail the following three concepts</p>
<ol>
<li>JavaScript Event Loop</li>
<li>requestAnimationFrame and rendering cycle</li>
<li>requestIdleCallBack</li>
</ol>
<p>In this article, I will attempt to document my learning about Event Loop. This topic might be particularly interesting to people who want to learn how NodeJS and Deno internals work. The next two topics are interesting to me for understanding how React works internally (for code base understanding). So, let's dive deep.</p>
<h2 id="javascript-execution-environment">JavaScript Execution Environment</h2>
<p>JavaScript is a single-threaded language. It executes one method at a time. Following high-level components are integral to its execution environment -</p>
<ol>
<li>Call Stack</li>
<li>Job Queues</li>
<li>Rendering Step</li>
<li>Microtasks</li>
<li>Event Loops</li>
</ol>
<p>Note: I have used runtime environment and execution environment interchangeably. At some points, I have used EcmaScript references. I am finding EcmaScript standards quite interesting. So, I thought to include those as well.</p>
<h3 id="call-stack">Call Stack</h3>
<p>Like other languages like C, C++, etc., JavaScript uses a <a target="_blank" href="https://262.ecma-international.org/6.0/#sec-execution-contexts">Call Stack</a> to execute methods. Whenever it decides to execute a method, it wraps the method in a stack frame and pushes the frame into the Call Stack. For any eventual sub-method calls, it keeps on pushing sub-methods into the stack (<em>LIFO</em> order). Once a method is executed, the corresponding stack frame is popped. Call Stack is an integral part of JavaScript for synchronous programming.</p>
<pre><code>test1();
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">test1</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Test 1 entry"</span>);
    test2();
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Test 1 exit"</span>);
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">test2</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Test 2 entry"</span>);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Test 2 exit"</span>)
}
</code></pre><p>For the above script, the result is as same as predicted:</p>
<pre><code><span class="hljs-attribute">Test</span> <span class="hljs-number">1</span> entry
<span class="hljs-attribute">Test</span> <span class="hljs-number">2</span> entry
<span class="hljs-attribute">Test</span> <span class="hljs-number">2</span> exit
<span class="hljs-attribute">Test</span> <span class="hljs-number">1</span> exit
</code></pre><p>But, JavaScript supports asynchronous programming. We can use setTimeout to execute something in the future like the below example. We could use the following code snippet that might trigger an alert and console.log() after 10s.</p>
<pre><code>    test1();
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">test1</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Test 1 entry"</span>);
        <span class="hljs-built_in">setTimeout</span>(test2, <span class="hljs-number">10000</span>);
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Test 1 exit"</span>);
    }
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">test2</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Test 2 entry"</span>);
        alert(<span class="hljs-string">"Test 2 execution"</span>);
    }
</code></pre><p>As expected, the result is </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1624265648320/3nph6r_jE.png" alt="Screenshot 2021-06-21 at 2.23.51 PM.png" /></p>
<p>Well, there was an alert as well. Following is the timeline of events</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1624266204462/mWCwELODd.png" alt="Screenshot 2021-06-21 at 2.30.37 PM.png" /></p>
<p>We can see the "Install Timer" at the bottom left. This is where the timer was installed to be fired after 10 seconds (10847ms). </p>
<p>It seems some thread is running in the background. Hold on! Did I not mention JavaScript is single-threaded? Let's see what could happen if JavaScript is multi-threaded. Suppose, in our hypothetical model, for the above JavaScript code execution, we are allowed to spawn a new thread for executing a single setTimeout. So, for one thousand setTimeout calls, we have a thousand threads. Each thread might attempt to change DOM as well independently. Now, if DOM is a shared resource for all the threads, multiple threads are bound to create chaos reading it at the same time. We would have spent most of our time debugging race conditions rather than building rich applications 😛. So, yes, JavaScript is single-threaded and it has served JavaScript and us well.</p>
<p>How come JavaScript schedule setTimeout callback after 10s then if there is no thread? The answer is Job or Task Queue. I am using both names interchangeably.</p>
<h3 id="job-queue">Job Queue</h3>
<p>With Es6, the concept of  <a target="_blank" href="https://262.ecma-international.org/6.0/#sec-jobs-and-job-queues">Job Queue</a> has been introduced. All the asynchronous tasks such as Mouse click, setTimeouts, etc., are pushed into the Job Queue for execution. JavaScript engine picks up tasks one by one and executes them using Call Stack (<em>FIFO</em> order).</p>
<h4 id="what-part-of-the-javascript-engine-picks-up-tasks-from-task-queue">What part of the JavaScript engine picks up tasks from Task Queue?</h4>
<p>The Event Loop. It runs in a loop throughout the life cycle of the app. It picks up tasks from the Task Queue and executes them with the help of Call Stack.</p>
<p>Note: My guess is the browser might maintain different queues for different kinds of event handling such as button clicks, mouse clicks, setTimeout calls, etc. Each browser can have different prioritization for each queue. It is just my guess. I am looking for ways to confirm that. I might write about that in the future.</p>
<h4 id="what-does-the-event-loop-do-when-there-is-nothing-in-call-stack-and-task-queue">What does the Event Loop do when there is nothing in Call Stack and Task Queue?</h4>
<p>You guessed it right - it runs in a loop.</p>
<h4 id="how-does-the-event-loop-know-if-it-needs-to-execute-something-from-task-queue">How does the Event Loop know if it needs to execute something from Task Queue?</h4>
<p>The Browser engine can enqueue a task in the relevant queue. The Event Loop, in the next rotation, can dequeue the task and execute it.</p>


<h4 id="what-happens-if-we-encounter-an-infinite-loop">What happens if we encounter an infinite loop?</h4>
<pre><code>    <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"demo"</span>&gt;</span>Trigger Alert<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
        <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"demo"</span>).addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function">() =&gt;</span> {
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Clicked"</span>);
            <span class="hljs-keyword">while</span>(<span class="hljs-literal">true</span>);
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"After loop is executed"</span>);
        });
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre><p>In the above example, the button click will enqueue the above synchronous script in Task Queue. In the next rotation, the Event Loop starts executing the task. Now, our script is stuck with <em>infinite while loop</em>. As a result, the Event Loop is stuck in the same position because of our infinite loop.</p>
<h3 id="rendering-step">Rendering Step</h3>
<p>Let's look into another aspect of the JavaScript runtime environment - the Rendering Step. Let's take the following example</p>
<pre><code><span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"test_paragraph"</span>&gt;</span> Test JS Hello<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>

        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"changeParagraphColor()"</span>&gt;</span>Trigger Alert<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
        <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">changeParagraphColor</span>(<span class="hljs-params"></span>) </span>{
              <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"test_paragraph"</span>).style.background = <span class="hljs-string">"red"</span>;
              <span class="hljs-keyword">var</span> top = <span class="hljs-number">100</span>, nested = <span class="hljs-number">1000</span>;
              <span class="hljs-keyword">for</span>(<span class="hljs-keyword">var</span> i=<span class="hljs-number">0</span>; i&lt;top; i++) {
                  <span class="hljs-keyword">for</span>(<span class="hljs-keyword">var</span> j=<span class="hljs-number">0</span>; j&lt;nested; j++) {
                      <span class="hljs-built_in">console</span>.log(i + <span class="hljs-string">":"</span> + j);
                  }
              }
              <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Changing color"</span>);
              <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"test_paragraph"</span>).style.background = <span class="hljs-string">"blue"</span>;
        }
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre><p>In the browser, we can see the following output.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1624807630595/sKsGkr4pB.png" alt="Screenshot 2021-06-27 at 8.56.51 PM.png" /></p>
<p>In the above example, the background color of the paragraph is changed to blue after the execution of the loop. The red background never takes effect. If I remove line 21, I can see the red paragraph, but after the execution of the script (including the loop). I expected to see first a paragraph with red background and then a blue. But I only saw, blue background.</p>
<p>Here, we are seeing the UI effect for the last line, but not the previous UI change. Why is that? That is because of the Rendering Step. The browser does not repaint the screen after the execution of each JavaScript code. It executes the above JavaScript code and collects all styling and UI changes. It applies final change (in this case line 21) in a single shot afterward, in the Rendering step. It is a step in the Event Loop that is executed independently. And initially, I thought the changes are happening so fast that my eyes could not catch them 😤. I will dive into the Rendering step in my next post.</p>
<h3 id="microtasks">Microtasks</h3>
<p>For now, I am associating Microtasks with JavaScript Promises. Promises are used to perform asynchronous operations in JavaScript. If you want to know more about Promises, visit this page for  <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">more details</a>. The tasks executed inside Promise are called <em>Microtasks</em>. Following is an example</p>
<pre><code>    <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"demo"</span>&gt;</span>Trigger Alert<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
        <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"demo"</span>).addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function">() =&gt;</span> {
            <span class="hljs-built_in">Promise</span>.resolve().then(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Micro Task 1"</span>));
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Task 1"</span>);
        });
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre><p>The above example will print the following output as expected. Microtask will be executed after all the synchronous tasks are executed.</p>
<pre><code><span class="hljs-attribute">Task</span> <span class="hljs-number">1</span>
<span class="hljs-attribute">Micro</span> Task <span class="hljs-number">1</span>
</code></pre><p>Let's look into another interesting example</p>
<pre><code>    &lt;body&gt;
        &lt;button id=<span class="hljs-string">"demo"</span>&gt;Trigger Alert&lt;/button&gt;
    &lt;/body&gt;
    &lt;script&gt;
        <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"demo"</span>).addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> {
            <span class="hljs-built_in">Promise</span>.resolve().<span class="hljs-keyword">then</span>(<span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Micro Task 1"</span>));
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Task 1"</span>);
        });
        <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"demo"</span>).addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> {
            <span class="hljs-built_in">Promise</span>.resolve().<span class="hljs-keyword">then</span>(<span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Micro Task 2"</span>));
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Task 2"</span>);
        });
    &lt;/script&gt;
</code></pre><p>Try guessing the output (take 5 seconds). If you guess the following output, it's perfectly alright! It is natural, intuitive, and we are human.</p>
<pre><code><span class="hljs-attribute">Task</span> <span class="hljs-number">1</span>
<span class="hljs-attribute">Task</span> <span class="hljs-number">2</span>
<span class="hljs-attribute">Micro</span> Task <span class="hljs-number">1</span>
<span class="hljs-attribute">Micro</span> Task <span class="hljs-number">2</span>
</code></pre><p>But the answer is</p>
<pre><code><span class="hljs-attribute">Task</span> <span class="hljs-number">1</span>
<span class="hljs-attribute">Micro</span> Task <span class="hljs-number">1</span>
<span class="hljs-attribute">Task</span> <span class="hljs-number">2</span>
<span class="hljs-attribute">Micro</span> Task <span class="hljs-number">2</span>
</code></pre><p>If you thought of the above answer, Congratulations! 😀 👍</p>
<h4 id="how-microtasks-are-executed">How microtasks are executed?</h4>
<p>Micro tasks are executed in two situations</p>
<ol>
<li>At the end of the synchronous script execution.</li>
<li>If the Call Stack is empty.</li>
</ol>
<p>For handling microtasks, JavaScript maintains another queue - Microtask Queue. For each call to Promise, an entry for each microtask is pushed into Microtask Queue. So, for the above example, the following will be the order</p>
<ol>
<li><em>Task 1</em> got pushed into Call Stack for synchronous execution. Also, <em>Microtask 1</em> is enqueued in the Microtask Queue.</li>
<li>After execution of <em>Task 1</em>, the Call Stack gets empty. So, it's the microtask time (condition 2 above)! If there were any other synchronous calls, <em>Microtask 1</em> would have been picked up after execution of those.</li>
<li>Microtask Queue is dequeued and the <em>Microtask 1</em> gets executed.</li>
<li>After step 3, the second handler gets called by Event Loop. The same thing repeats for the second microtask.</li>
</ol>
<h2 id="what-are-event-loops">What are Event Loops?</h2>
<p>I know you might be thinking what am I talking about for this long. Nowadays, all browsers create a separate event loop for each browser tab. Collectively these are called <strong>Event Loops</strong>. At first, Chrome started doing this. Others followed soon. </p>
<h3 id="impact-of-event-loops">Impact of Event Loops</h3>
<p>I have seen one unresponsive page causing the entire browser to get stuck in Firefox's earlier version. I have never seen this issue with Chrome. Chrome has a separate JavaScript environment for each tab from early versions I believe. The browser might require more resources to do this. But I think, it is worth the better and richer experience.😌</p>
<h3 id="interesting-usecase-opening-a-page-in-a-separate-new-tab">Interesting Usecase: Opening a page in a separate new tab</h3>
<p>Let's assume, for the below three examples, <em>target_page</em> contains an infinite loop.</p>
<pre><code><span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"target_page"</span> <span class="hljs-attr">target</span>=<span class="hljs-string">"_blank"</span>&gt;</span>New Target Page<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
</code></pre><p>For the earlier version browser, for the above scenario, the <em>target_page</em> and <em>current page</em> used to share the same Event Loop for all the JavaScript tasks. As a result, if the <em>target_page</em> is containing an infinite loop, both the <em>current</em> and <em>target_page</em> got stuck in an infinite loop as well. Both the pages used to become unresponsive. The workaround proposed</p>
<pre><code><span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"target_page"</span> <span class="hljs-attr">target</span>=<span class="hljs-string">"_blank"</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"noopener"</span>&gt;</span>New Tab<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
</code></pre><p>Upon setting "rel=noopener", each page gets separate environment. It was introduced to reduce the impact of untrusted pages containing malicious JavaScript, which might affect the current page. Now, all the browsers have started implementing this behavior by default ( <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTML/Link_types/noopener">relevant MDN doc</a>). I have tested with the latest Chrome. It is implemented there.</p>
<p>Also, for this example,</p>
<pre><code><span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"target_page"</span>&gt;</span>New Tab<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
</code></pre><p>If you open <em>target_page</em> in a new tab (by right click on the mouse), both the pages share the same JavaScript runtime environment. So, if <em>target_page</em> has an infinite loop, both the pages get stuck.</p>
<h2 id="conclusion">Conclusion</h2>
<p>The Event Loop is an interesting and critical component for understanding any JavaScript run time environments. I am building up my knowledge on React JS and Node JS internals upon this. If you have enjoyed the article, do give me thumbs up. In case of any questions, let me know in the comments.</p>
<p>Happy learning! 😀</p>
<h2 id="references-for-further-reading">References for further reading</h2>
<ol>
<li><a target="_blank" href="https://262.ecma-international.org/6.0/">EcmaScript Standard</a> - EcmaScript standard has documentation around how each component such as Job Queues, Call Stack should be implemented. I find these details particularly interesting.</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[Abstract Introduction to React Internals]]></title><description><![CDATA[React is a rich JavaScript framework. I think it's necessary to know a high-level internal working of a language or a framework to use it effectively. React's performance comes from its internal data structures and algorithms. In this article, I will...]]></description><link>https://blog.thecuriouscoder.in/abstract-introduction-to-react-internals</link><guid isPermaLink="true">https://blog.thecuriouscoder.in/abstract-introduction-to-react-internals</guid><category><![CDATA[React]]></category><category><![CDATA[React Native]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Beginner Developers]]></category><category><![CDATA[Tutorial]]></category><dc:creator><![CDATA[Subhasish Kundu]]></dc:creator><pubDate>Sat, 05 Jun 2021 11:11:34 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1622884179097/B5XT4oIOX.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>React is a rich JavaScript framework. I think it's necessary to know a high-level internal working of a language or a framework to use it effectively. React's performance comes from its internal data structures and algorithms. In this article, I will not touch upon the actual codebase, data structures, or algorithms. I will share, on a high level, how React 16 renders and updates the UI. So, let's get started!</p>
<blockquote>
<p>Smart data structures and dumb code works a lot better than the other way around. - Eric S. Raymond</p>
</blockquote>
<h2 id="internal-representation-of-components">Internal Representation of Components</h2>
<p>During parsing, React creates an in-memory representation of components for easy rendering and updating. Typical React components can have multiple children and sibling components. We have multiple options to represent a component.</p>
<ol>
<li>N-ary tree.</li>
<li>Multi-linked doubly linked list.</li>
</ol>
<h3 id="sample-component">Sample Component</h3>
<div class="gist-block embed-wrapper" data-gist-show-loading="false" data-id="15e103ce9dea25c4817ed012740729ff"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a href="https://gist.github.com/15e103ce9dea25c4817ed012740729ff" class="embed-card">https://gist.github.com/15e103ce9dea25c4817ed012740729ff</a></div><h3 id="representation-of-the-component">Representation of The Component</h3>
<p>The following diagram shows the internal representation for the above component using both data structures. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1622879498150/5yXjKc_DU.png" alt="BlogPosts (2).png" /></p>
<p>For both the data structures, </p>
<ul>
<li>we can represent the parent-child relationship vertically.</li>
<li>we can represent sibling relationships horizontally.</li>
<li>all the relationships are bidirectional for easy traversal. </li>
</ul>
<p>One thing to note - I am taking a component for simplicity. I am not taking the entire page into the scope.</p>
<h2 id="rendering-and-updating-react-component">Rendering and Updating React Component</h2>
<p>There can be two types of rendering - simple rendering without any updates or rendering page components after updates in a dynamic UI. Let's see how each scenario works.</p>
<h3 id="simple-rendering-without-updates">Simple Rendering without Updates</h3>
<p>In this case, React can use a combination of Depth-First and Breadth-First Traversal to render the entire component (for both types of representation).</p>
<h3 id="handling-ui-changes">Handling UI Changes</h3>
<p>In a dynamic user interface, we will have periodic updates as well as other high-priority activities like network calls. It is possible while rendering current changes, some other high-priority tasks come up. In that case, React may have to do a context switch. And that's where React shines. How does React handle that? Let's jump into that.</p>
<p><em>[I will use <strong>representation</strong> and <strong>DS</strong> (for data structure) inter-changeably.]</em></p>
<h4 id="rendering-phase">Rendering Phase</h4>
<p>Let's call the original representation <em>current copy</em>. Let's go step by step.</p>
<ol>
<li>Engine starts cloning the <em>current copy</em> into another DS by traversal. Let's call it <em>work-in-progress copy</em>.</li>
<li>If there is any change in any Node, it can tag the updated Node during traversal. It can store the updates in a separate internal DS like a list. Let's call it <em>effects list</em>.</li>
</ol>
<p>Let's assume, for our example, <em>Logo</em>,  <em>About Us</em>, and <em>Products</em> sub-components have changed after this operation. In that case, the following can be the <em>effects list</em>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1622888946045/LXypOKvMU.png" alt="Blog post List (3).png" /></p>
<p><strong>Why not update the UI while traversal?</strong>
Let's suppose, the user creates an animation with tasks A and B. React is supposed to render A and B consecutively for creating a rich experience. Now, a high-priority task has arrived between A and B. Engine cannot ignore it. If the engine has to perform it between A and B by stopping B, the user will see a glitch between A and B. It is not desired user experience.</p>
<p><strong>Why collect updates in a separate DS?</strong>
As a high-priority task may arrive in between, rendering may not be as important as that task. In that case, React should switch context. After finishing that task, it can resume the traversal again. This collection of updates will help React to start the operation easily again.</p>
<h4 id="commit-phase">Commit Phase</h4>
<p>After the collection of updates in a DS, it's time for applying the changes. It has to go in one shot. Otherwise, the user will see glitches and partial updates.</p>
<ol>
<li>We can traverse the <em>effects list</em> and apply the updates in the actual UI. It has to be synchronous operation.</li>
<li>Once everything is done, React needs to store the updated DS in <em>current copy</em> to represent the current UI. How to do that? Yes, you guessed it right - point <em>current copy</em> to <em>work-in-progress copy</em>.</li>
</ol>
<p>The above steps complete the entire update cycle. React engine applies various optimizations. We will explore React internals in detail in the next post. I promise I will touch on React data structures and codebase.</p>
<h3 id="notes">Notes</h3>
<ol>
<li>React uses the Multi-Linked Doubly Linked List representation internally.</li>
<li>I have used nomenclature used by React teams like <em>current copy</em>, <em>work-in-progress copy</em>, and <em>effects list</em>. Naming is always harder. They did a good job with these names. So, I just used the names.</li>
<li>In React 15, React used to perform partial updates as I mentioned in <em>Why not update the UI while traversal?</em> section. In React 16, they have changed the algorithm.</li>
<li>Using an <em>effects list</em> kind of DS in compiler is quite interesting. It is worth a separate post. I have seen this pattern to execute a bunch of assembly code for showing the final updates to the user for low-level language compilation. It is a great example of the power of simple data structures like Linked List. Let me know if you want to know more about this technique in the comments. I will try to create a post on that particularly.</li>
<li>Check out my article about  <a target="_blank" href="https://curiouscoder.hashnode.dev/virtual-dom-in-react-an-easy-introduction">React Virtual DOM</a>.</li>
</ol>
<p>If you enjoyed the article, please don't forget to like it. In case you have any doubts, ask in the comment section.</p>
<p>Happy Learning! 😀</p>
]]></content:encoded></item><item><title><![CDATA[How Virtual DOM is Powering React Performance?]]></title><description><![CDATA[I have been doing front-end web development for last year only. Lately, I started playing with ReactJS. I have worked on vanilla JavaScript and jQuery for quite some time. My expert colleague at Amazon suggested I explore React. My only sin was I sai...]]></description><link>https://blog.thecuriouscoder.in/how-virtual-dom-is-powering-react-performance</link><guid isPermaLink="true">https://blog.thecuriouscoder.in/how-virtual-dom-is-powering-react-performance</guid><category><![CDATA[React]]></category><category><![CDATA[virtual dom]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[javascript framework]]></category><dc:creator><![CDATA[Subhasish Kundu]]></dc:creator><pubDate>Wed, 02 Jun 2021 20:10:44 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1622663512976/hv3BfGY3g.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I have been doing front-end web development for last year only. Lately, I started playing with ReactJS. I have worked on vanilla JavaScript and jQuery for quite some time. My expert colleague at Amazon suggested I explore React. My only sin was I said, <em>"Can't we have an abstraction over jQuery?"</em></p>
<p>I have heard about React for a long time. The overwhelming number of tutorials on React made my learning very easy. I apologize to myself for not starting early. But better late, than never.</p>
<p>I have worked on compilers for a long time. So, while exploring a new language, I try to think how an interpreter or compiler might do the trick. After learning syntax, I started exploring how React is improving performance. And I encountered Virtual DOM. </p>
<p><em>[In this article, I will try to explain how virtual DOM might work with respect to a compiler. I will not go into any specific details. I am still learning how React is implemented. I will keep posting details.]
</em></p>
<h2 id="document-object-model-or-dom">Document Object Model or DOM</h2>
<p>A tree of individual components that the browser creates upon receiving an HTML response from a server. JavaScript provides us ways to manipulate DOM to get the desired effect like displaying a div on clicking a button (<a target="_blank" href="https://codepen.io/subhakundu10/pen/bGqLMPX">Codepen sample</a>).</p>
<p>The above operation is expensive as the browser manipulating the DOM tree each time some changes are applied. I believe the browser has to do some smart computation for identifying the changed element and making the changes (like suppose, keeping a reference to each element in a hash map. I am still exploring it.). It is definitely an expensive operation - time and memory-wise. Also, the browser has other tasks to do like displaying the page.</p>
<h2 id="what-is-virtual-dom">What is Virtual DOM?</h2>
<p>"The virtual DOM (VDOM) is a programming concept where an ideal, or “virtual”, representation of a UI is kept in memory and synced with the “real” DOM by a library such as ReactDOM." -  <a target="_blank" href="https://reactjs.org/docs/faq-internals.html">React Documentation</a> .</p>
<p>I did not even try to define it with my words. It is such a concise definition. What I have understood so far - React virtual DOM is an in-memory optimized representation of DOM. And React engine deals with low-level APIs to apply the changes.</p>
<h2 id="how-react-brings-performance-into-picture">How React brings Performance into Picture?</h2>
<p>Now, with the above concept, let's bring the compiler into the picture.</p>
<p>Every compiler stores an entire program in some form of representation (Abstract Syntax Tree). I am mapping Virtual DOM to AST (I am still learning how React optimizes). As virtual DOM is an in-memory representation, React engine or compiler can access it fast.  Now, let's go step by step.</p>
<ol>
<li>Now, if there is some change - React changes virtual DOM. </li>
<li>React engine compares the virtual DOM with real DOM (aka  <a target="_blank" href="https://reactjs.org/docs/reconciliation.html">"diffing"</a>) and applies the changes to the changed part only. It finds out the changes.</li>
<li>It applies the changes using low-level APIs directly (like the JavaScript engine does for our code).</li>
</ol>
<p>React engine can apply optimizations in all three steps because virtual DOM representation is in its control. React engine is actually a very advanced JavaScript engine. With syntax and semantics of React, it can fasten the performance. </p>
<p>Now, in JS, the browser is doing all the work. Also, to some extent, it is dependent on how code is being written. In the case of React, React engine is <strong><em>abstracting</em></strong> (remember the word I mentioned at the beginning) out all optimization.</p>
<p>This is one of the reasons, React is faster than traditional HTML JS webpages. I know technically everything I mentioned might not be true and I have not touched upon a lot of things. As I keep exploring, I will keep posting my findings in detail. I will see how my concepts get cleared on the way. If you enjoyed the article, give a like and subscribe to my newsletter.</p>
<p>Happy learning! </p>
]]></content:encoded></item></channel></rss>