<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sadid Khan on Medium]]></title>
        <description><![CDATA[Stories by Sadid Khan on Medium]]></description>
        <link>https://medium.com/@sadidkhan?source=rss-662503abfddb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*4Ki180we51ju-iZqOG5Mjg.jpeg</url>
            <title>Stories by Sadid Khan on Medium</title>
            <link>https://medium.com/@sadidkhan?source=rss-662503abfddb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 20:16:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sadidkhan/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[LeetCode #198: House Robber]]></title>
            <link>https://medium.com/@sadidkhan/leetcode-198-house-robber-d64bc069d6dd?source=rss-662503abfddb------2</link>
            <guid isPermaLink="false">https://medium.com/p/d64bc069d6dd</guid>
            <category><![CDATA[leetcode-198]]></category>
            <category><![CDATA[coding-interviews]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[house-robber]]></category>
            <category><![CDATA[dynamic-programming]]></category>
            <dc:creator><![CDATA[Sadid Khan]]></dc:creator>
            <pubDate>Sat, 23 Aug 2025 11:07:08 GMT</pubDate>
            <atom:updated>2025-10-14T10:10:50.834Z</atom:updated>
            <content:encoded><![CDATA[<p>The <a href="https://leetcode.com/problems/house-robber/">House Robber problem (LeetCode #198)</a> is one of the most popular problems to learn dynamic programming concepts. In this post, I will start by explaining the problem in simple terms. Then, I will walk through the thinking process behind solving it, so you can see how to break it down into smaller steps.</p><p>Once the idea is clear, I will first show the recursive solution. This version is easier to understand conceptually, but it is not the most efficient. After that, I will move on to the faster iterative solution, which improves both speed and memory usage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w30bOM_3FF16Ji7HF2W5Sg.png" /></figure><p>For both solutions, I have used Python to keep the implementation straightforward.</p><h3>Let’s understand the problem first</h3><p>You’re a robber hitting houses on a street. Each house has some cash, given in an array <em>nums</em>. But you can not rob next-door houses because of a security system. Your job is to grab the most money possible and return that amount.</p><p><strong>Example</strong>:</p><ul><li>Input: nums = [2,7,9,3,1]</li><li>Output: 12</li><li>Explanation: <br>Rob house 1 (means the house nums[0] from which we will get 2) and house 3 (9) to obtain 2 + 9 = 11. <br>Or rob house 2 (7) and house 4 (3) for 7 + 3 = 10. The max is 12.</li></ul><h3>How to Solve It</h3><p>For each house, you decide: rob it or skip it. This choice depends on which option gives you more money:</p><ul><li><strong>Rob house </strong><strong>i</strong>: You can’t rob house<em>i-1</em>, so you take the money from the house <em>i</em> (<em>nums[i]</em>) plus the maximum money you could get from houses up to <em>i-2</em>.</li><li><strong>Skip house </strong><strong>i</strong>: You keep the maximum money from houses up to<em> </em><em>i-1</em>.</li></ul><p>So the choice is whichever pays more. In shorthand:</p><blockquote>dp[i]=max⁡(dp[i−1], dp[i−2]+nums[i])</blockquote><p>We’ll start with a simple <strong>recursive</strong> version to see the idea, and then switch to a <strong>faster iterative</strong> version that uses constant space.</p><h3>Recursive Solution (with Memoization)</h3><p>We write a function <em>robPlan(i)</em> that gives the maximum money you can get up to house i. Here’s the plan:</p><ul><li>If i &lt; 0 (no houses), return 0.</li><li>If i = 0, return the money in the first house.</li><li>So, for housei, take the max of <em>robPlan(i-1)</em> and <em>robPlan(i-2) + nums[i]</em>.</li><li>Use a dictionary to save results so we don’t repeat the calculation.</li></ul><p><strong>Code</strong>:</p><pre>class Solution:<br>    def rob(self, nums: List[int]) -&gt; int:<br>        if not nums:<br>            return 0<br>        dict = {}<br>        return self.robPlan(nums, len(nums) - 1, dict)<br>    <br>    def robPlan(self, nums, i, dict):<br>        if i &lt; 0:<br>            return 0<br><br>        if i == 0:<br>            return nums[0]<br><br>        if i in dict:<br>            return dict[i]<br><br>        prev2 = self.robPlan(nums, i - 2, dict) + nums[i]<br>        prev1 = self.robPlan(nums, i - 1, dict)<br>        dict[i] = max(prev2, prev1)<br><br>        return dict[i]</pre><p><strong>How It Works</strong>:</p><ul><li>Start at the last house (i = len(nums)-1).</li><li>For each house, check if we should rob it or skip it (described the logic above)</li><li>Save results in <em>dict</em>to avoid doing the same calculation over and over.</li></ul><p><strong>Complexity</strong>:</p><ul><li><strong>Time</strong>: O(n) — we solve each house once.</li><li><strong>Space</strong>: O(n) for the memo dictionary and recursion stack.</li></ul><h3>Iterative Solution (Simpler and Faster)</h3><p>The recursive way is clear but a bit slow because of function calls. We can do the same thing with a loop and just two variables: prev1 (max money up to the last house) and prev2 (max money up to two houses ago). This saves space and runs faster.</p><p><strong>Code</strong>:</p><pre>class Solution:<br>    def rob(self, nums: List[int]) -&gt; int:<br>        if not nums:<br>            return 0<br><br>        if len(nums) == 1:<br>            return nums[0]<br><br>        prev2 = nums[0]<br>        prev1 = max(nums[0], nums[1])<br><br>        for i in range(2, len(nums)):<br>            current = max(prev1, prev2 + nums[i])<br>            prev2 = prev1<br>            prev1 = current<br><br>        return prev1</pre><p><strong>How It Works</strong>:</p><ul><li>Set prev2 to the first house’s money and prev1 to the max of the first two houses.</li><li>For each house i, pick the max of skipping it (<em>prev1</em>) or robbing it (<em>prev2 + nums[i]</em>).</li><li>Update <em>prev2 </em>and <em>prev1 </em>each time.</li><li><strong>Handle edge cases</strong>: <strong><em>empty array (0) or one house (nums[0])</em></strong>.</li></ul><p><strong>Complexity</strong>:</p><ul><li><strong>Time</strong>: O(n) — one loop through the array.</li><li><strong>Space</strong>: O(1) — only two variables.</li></ul><h3>Why should we choose Iterative?</h3><p>The iterative solution is better because:</p><ul><li>It’s faster (no recursion overhead).</li><li>It uses less memory (just two variables, not a dictionary).</li><li>It’s easier to follow and debug.</li></ul><h3>Quick Tips</h3><ul><li><strong>Recursive First</strong>: Start with recursion to understand the problem.</li><li><strong>Iterative for Speed</strong>: Switch to a loop to make it efficient.</li><li><strong>Edge Cases</strong>: Check for empty arrays and single houses.</li></ul><p>Currently, I am solving problems on LeetCode to improve my problem-solving skills. While learning, I am also writing notes for myself, and thought of sharing them here in case they help others too. Since I mainly write these notes for myself, this post might not be as detailed as some others you will find on the internet. Still, I hope it makes the House Robber problem easier to understand and solve. Give it a try on LeetCode — and happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d64bc069d6dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unit Testing in C#, a review of xUnit.net]]></title>
            <link>https://medium.com/@sadidkhan/review-of-xunit-net-072420a54ad0?source=rss-662503abfddb------2</link>
            <guid isPermaLink="false">https://medium.com/p/072420a54ad0</guid>
            <dc:creator><![CDATA[Sadid Khan]]></dc:creator>
            <pubDate>Fri, 18 Jul 2025 11:19:02 GMT</pubDate>
            <atom:updated>2025-09-08T09:21:59.771Z</atom:updated>
            <content:encoded><![CDATA[<p>Unit testing is a crucial module of the modern software development lifecycle, which is mostly done by developers. It involves testing individual units of the codebase to ensure that they work as expected. Unit testing is essential because of its ability to catch bugs early, improve code quality, and ensure that software functions correctly under various conditions.</p><p>Unit tests are the first line of defense against these problems. It provides a structured way to test individual components and the logic flow of a system before they are integrated into larger systems.</p><p>In this report, we will examine <strong>xUnit.net</strong>, a popular unit testing framework for the .NET ecosystem. We will discuss the motivation behind unit testing, the general process of unit testing, the step-by-step process of using xUnit.net for unit testing, and the benefits and limitations of the tool.</p><h3>Motivation for Unit Testing</h3><p>The primary motivation of unit testing is to verify that the individual components of a program, or the “units” of the code, perform as expected. These tests help to detect the issues earlier and prevent errors from propagating into larger, more complex systems. The earlier detection reduces the cost of bug fixing during later stages of development or after deployment. Some of the core motivations for adopting unit testing include:</p><ol><li><strong>Early Detection of Bugs:</strong> Unit testing helps identify bugs early in the development lifecycle. By detecting bugs as soon as possible, developers avoid having to debug issues that might be harder to isolate once the code has been integrated into larger systems.</li><li><strong>Improved Code Quality:</strong> Writing tests encourages developers to write modular, clean, and maintainable code. With unit tests, developers are more likely to design code that can be easily tested and changed without causing unintended side effects.</li><li><strong>Facilitates Refactoring:</strong> Unit tests work as a safeguard for developers when refactoring code. By running the tests before and after refactoring, developers can ensure they have not accidentally broken any existing working functionality.</li><li><strong>Better Documentation:</strong> Unit tests serve as a live documentation of code behavior. By reviewing the tests, developers can quickly understand the expected behavior of functions and methods, which can be especially valuable in large codebases.</li><li><strong>Supports Test-Driven Development (TDD):</strong> TDD is a software development methodology where developers write tests before writing feature code. The tests guide the development process and also ensure that code is written by keeping testing in mind from the start.</li></ol><h3>How to Perform a Unit Test</h3><p>Performing a unit test involves writing specific tests to ensure that individual components of software work as expected. The first step is to plan and understand the functionality of the method or the class we want to test. Each test case is designed to verify that a single unit of functionality functions correctly. A unit test is typically written for each method in your code to check if the method behaves as expected for predefined inputs. The test case will include an <strong>assertion</strong>, which checks if the actual output of the method matches the expected result.</p><p>A test class holds all the unit tests related to a particular class or functionality. Each test method in the class corresponds to a specific method or behavior of the code being tested. In <strong>xUnit.net</strong>, test methods are decorated with the [Fact] attribute. A test class typically initializes the class or component under test in its constructor.</p><p>Unit testing generally follows the <strong>Arrange, Act, Assert</strong> (AAA) pattern:</p><ol><li><strong>Arrange</strong>: This step involves setting up the required environment for the test, such as creating instances of objects, mocking, setting parameters, or preparing data that will be used during the test.</li><li><strong>Act</strong>: In this step, the method or functionality being tested is executed with the arranged inputs.</li><li><strong>Assert</strong>: After the method is executed, the test checks whether the actual result matches the expected result. If the results don’t match, the test fails.</li></ol><h3>Demonstrating the Procedure of Using xUnit.net</h3><p>Now that we have the basics of performing unit tests, let’s go over how to set up and run tests with xUnit.net specifically, using the steps mentioned earlier.</p><h4>Step-by-Step Procedure Using xUnit.net</h4><p>To demonstrate how to use xUnit.net for unit testing, I’ll walk you through setting up a simple .NET project with a Calculator class and corresponding unit tests using xUnit.net.</p><p><strong>Step 1: Create a .NET Project</strong></p><ul><li>Open Visual Studio</li><li>Create a new Console Application project. You can name it UnitTestProject.</li></ul><p><strong>Step 2: Install xUnit.net</strong></p><ul><li>Open the NuGet Package Manager in Visual Studio.</li><li>Search for xunit and install the xunit NuGet package.</li><li>Install xunit.runner.visualstudio to enable test execution from Visual Studio.</li><li>Install Microsoft.NET.Test.Sdk</li></ul><p><strong>Step 3: Write a Function Class</strong></p><ul><li>Consider the following simple program that performs basic arithmetic operations:</li></ul><pre>namespace UnitTestSampleProject<br>{<br>    public class Calculator<br>    {<br>        public int Add(int a, int b) =&gt; a + b;<br>        public int Subtract(int a, int b) =&gt; a - b;<br>        public int Multiply(int a, int b) =&gt; a * b;<br>        public double Divide(int a, int b)<br>        {<br>            if (b == 0) throw new DivideByZeroException(&quot;Cannot divide by zero&quot;);<br>            return (double)a / b;<br>        }<br>    }<br>}</pre><p><strong>Step 4: Write Unit Tests Using xUnit.net</strong></p><p>The following image shows the <strong><em>CalculatorTests.cs</em></strong> that has all test cases to cover the functionality and flow path of the methods listed in the <strong><em>Calculator.cs</em></strong> class.</p><pre>using System;<br>using System.Collections.Generic;<br>using System.Linq;<br>using System.Text;<br>using System.Threading.Tasks;<br>using Xunit;<br><br>namespace UnitTestSampleProject.Tests<br>{<br>    public class CalculatorTests<br>    {<br>        private Calculator _calculator;<br><br>        public CalculatorTests() =&gt; _calculator = new Calculator();<br><br>        [Fact]<br>        public void Add_ShouldReturnCorrectResult()<br>        {<br>            Assert.Equal(7, _calculator.Add(3, 4));<br>        }<br><br>        [Fact]<br>        public void Subtract_ShouldReturnCorrectResult()<br>        {<br>            Assert.Equal(5, _calculator.Subtract(10, 5));<br>        }<br><br>        [Fact]<br>        public void Multiply_ShouldReturnCorrectResult()<br>        {<br>            Assert.Equal(12, _calculator.Multiply(4, 3));<br>        }<br><br>        [Fact]<br>        public void Divide_ShouldReturnCorrectResult()<br>        {<br>            Assert.Equal(3, _calculator.Divide(9, 3));<br>        }<br><br>        [Fact]<br>        public void Divide_ByZero_ShouldThrowException()<br>        {<br>            Assert.Throws&lt;DivideByZeroException&gt;(() =&gt; _calculator.Divide(9, 0));<br>        }<br>    }<br>}</pre><p><strong>Step 5: Running the Tests</strong></p><p>The last phase is running and analyzing the test cases. After writing the tests, you can run them to verify that they work as expected.</p><p>In Visual Studio:</p><ul><li>Open the Test Explorer window (Test &gt; Windows &gt; Test Explorer).</li><li>Click Run All to execute all tests in the project.</li></ul><p>The results will appear in the <strong>Test Explorer</strong>, where you can see which tests passed or failed.</p><p>In this test suite, each method of the Calculator class is tested with a separate unit test. The <strong><em>Divide_ByZero_ShouldThrowException</em></strong> test checks that an exception is thrown when attempting to divide by zero. From the test explorer, you can run one or all test case methods altogether in one click. Figure 1 shows how my test explorer looks after running all the test cases. The green check mark shows that all my test cases passed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/0*qlXE4DPjLEobskHa" /><figcaption><em>Figure 1: Test Explorer view of my CalculatorTests class</em></figcaption></figure><h3>Advantages of xUnit.net</h3><p>xUnit.net is a very flexible tool for unit testing in the .NET ecosystem, especially for large projects.</p><ol><li><strong>Lightweight and Easy to Use</strong>: xUnit.net is simple to set up and use. It integrates easily with Visual Studio and .NET Core projects. Its syntax is clean and easy to read, which makes it an excellent choice for both beginners and experienced developers.</li><li><strong>Parallel Test Execution</strong>: xUnit.net runs tests in parallel by default, which can significantly speed up testing in larger codebases. For instance, tests like <strong><em>Add_ShouldReturnCorrectResult()</em></strong> and <strong><em>Subtract_ShouldReturnCorrectResult()</em></strong> run at the same time by default, which gives a significant performance boost.</li><li><strong>Rich Assertion Library</strong>: The framework provides a wide range of assertions, making it easy to test various conditions. For example, xUnit.net provides assertions like <strong><em>Assert.Equal</em></strong>, <strong><em>Assert.NotNull</em></strong>, <strong><em>Assert.Throws</em></strong>, and many others that help to validate various conditions.</li><li><strong>Active Community and Frequent Updates</strong>: xunit.net has a strong community base. We can get help from the community forum, GitHub issues, or Stack Overflow to find solutions. Additionally, the framework is regularly updated to support new versions of NET.</li></ol><h3>Sample Project</h3><p>Github link:<a href="https://github.com/sadidkhan/UnitTestProject"> https://github.com/sadidkhan/UnitTestProject</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=072420a54ad0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode: Longest Palindromic Substring]]></title>
            <link>https://medium.com/@sadidkhan/longest-palindromic-substring-ff8d87da61a3?source=rss-662503abfddb------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff8d87da61a3</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[leetcode-medium]]></category>
            <category><![CDATA[coding-interviews]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Sadid Khan]]></dc:creator>
            <pubDate>Thu, 17 Jul 2025 09:03:56 GMT</pubDate>
            <atom:updated>2025-07-17T09:31:59.970Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently, I started solving <a href="https://leetcode.com/problem-list/rr2ss0g5/">Neetcode 150</a> problems and came across the problem <a href="https://leetcode.com/problems/longest-palindromic-substring/description/"><em>Longest Palindromic Substring</em></a>. Although there are plenty of resources available to learn and solve it, it still took me some time to work through the solution. So, I decided to write a blog post to help others understand the problem and how to solve it.</p><p>As an engineer myself, most of the time I skip lengthy explanations and jump straight to the sections. So, in this post, I will try to keep the description short and to the point.</p><p>The problem statement is straightforward. It asks us to find the longest substring that is a Palindrome.</p><h3>What is a palindrome?</h3><p>A sequence that is the same from forward and backward. For example: “ababa”. It would be the same in either direction.</p><ol><li>In forward direction ==&gt; ababa</li><li>In backward direction &lt;== ababa</li></ol><h3>Problem Overview</h3><p>We need to find the longest palindromic substring.</p><p>Input: s = “babad” → Output: “bab” (or “aba”, both length 3)</p><p>Input: s = “cbbd” → Output: “bb” (length 2)</p><p>There are multiple ways to solve this problem, but here we will use the “<strong><em>Expand Around Center</em></strong>” approach. In this method, we consider each character in the string (and the gap between each pair of characters) as a potential center of a palindrome. We then expand outward from the center in both directions to check for the longest possible palindrome.</p><h3>Approach: Expand Around Center</h3><p>A palindrome is symmetric around a center. There are two types:</p><ol><li>Odd-length palindromes: Centered at a single character (e.g., “aba” is centered at ‘a’).</li><li>Even-length palindromes: Centered between two characters (e.g., “bb” is centered between the ‘b’s).</li></ol><p>For a string of length n, there are:</p><ul><li>n centers for odd-length palindromes (one per character).</li><li>n-1 centers for even-length palindromes (one per gap between consecutive characters).</li><li>Total: 2n — 1 centers.</li></ul><p>For example, string s = “”babad”</p><ul><li>n = 5</li><li>For odd-length palindromes, each character will be considered as the center. Odd centers: At b, a, b, a, d (5 centers)</li><li>For even-length palindromes, each gap between two characters will be considered as the center. Even centers: b - a - b - a - d (consider ‘-’ as a gap between each character, 4 centers)</li><li>Total 5 + 4 = 9 centers</li></ul><h3>Steps:</h3><ol><li>Loop through each index i from 0 to n-1.</li><li>For each i :<br>- Check odd-length palindrome: Center at i. <br>- Check even-length palindrome: Center between i and i+1.</li><li>Expand around each center while characters match and indices are within bounds.</li><li>Track the longest palindrome’s start index and length.</li><li>Return the substring.</li></ol><pre>class Solution:<br>    def longestPalindrome(self, s):<br>        n = len(s)<br>        max_len = 0<br>        start = 0<br>        for i in range(n):<br>        <br>          # first we will check the odd length palindrome<br>            left = i<br>            right = i<br>            while(left&gt;=0 and right&lt;n and s[left] == s[right]):<br>                left = left - 1<br>                right = right + 1<br>            <br>            # when the loop ends, left and right is out of palindrome bound, So,<br>            left = left + 1<br>            right = right - 1<br>            <br>            length = right - left + 1 #calculating the length<br>            if(length &gt; max_len):<br>                max_len = length // new length is greater so, update max_len here<br>                start = left // update start pointer<br>                <br>            # Now we will check the even length palindrome<br>            left = i<br>            right = i+1<br>            <br>            while(left&gt;=0 and right&lt;n and s[left] == s[right]):<br>                left = left - 1<br>                right = right + 1<br><br>            # when the loop ends, left and right is out of palindrome bound, So,<br>            left = left + 1<br>            right = right - 1<br>            length = right - left + 1<br>            <br>            if(length &gt; max_len):<br>                max_len = length<br>                start = left<br><br>        return s[start: start+max_len] </pre><h3>How It Works:</h3><ul><li>Initialize variables, Set n = len(s), start = 0, max_len = 0</li><li>Loop over each character, considering it as the center of a palindrome. For each index i (0 to n-1):<br>- <strong>Odd case</strong>: Set left = i, right = i (center at s[i]).<br>- <strong>Even case</strong>: Set left = i, right = i + 1 (center between s[i] and s[i+1]).</li><li>While left &gt;= 0, right &lt; n, and s[left] == s[right], expand by decrementing left and incrementing right.</li><li>After expansion, left is one index before the palindrome’s start, and right is one index after its end. So, we need to adjust the boundary and compute length</li><li>Adjust: left += 1 (start), right -= 1 (end).</li><li>Length: right — left + 1 (inclusive range).</li><li>Update start and max_len if the current palindrome is longer.</li><li>Now we know the start index of the palindrome and its length. So, returning s[start: start+max_len]</li></ul><h3>Key Concepts</h3><ul><li><strong>2n — 1 Centers</strong>: We check n odd centers (each character) and n-1 even centers (gaps), ensuring we find all palindromes.</li><li><strong>Length Calculation</strong>: After expansion, left and right are outside the palindrome. Adjust to the boundaries (left += 1, right -= 1), then length is right — left + 1.</li><li><strong>Time Complexity</strong>: O(n²) — n iterations, each with up to O(n) expansion.</li><li><strong>Space Complexity</strong>: O(1) — only a few variables.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff8d87da61a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular: Component Inheritance]]></title>
            <link>https://medium.com/@sadidkhan/angular-component-inheritance-888c2a2d3b27?source=rss-662503abfddb------2</link>
            <guid isPermaLink="false">https://medium.com/p/888c2a2d3b27</guid>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Sadid Khan]]></dc:creator>
            <pubDate>Sun, 06 Sep 2020 20:21:02 GMT</pubDate>
            <atom:updated>2020-09-06T20:41:11.973Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*igf60WpMbSw_CKg8NueP9g.jpeg" /></figure><p>Currently we are using Angular in front-end to develop our admin app. A few days ago, while reviewing my pull request in github, one of my team mate found some duplicate code in different component. This is a very common scenario of code review. But while solving the redundancy as per review comment I came to know about “Component Inheritance”. I found it interesting and here I am to share my learning on this.</p><p>In Angular component, inside ngOnInit(), we usually subscribe subject, sometimes the function we pass inside subscribe(), is duplicate in different component. We are going to create the duplication and later solve that using Component Inheritance.</p><h3>Scenario</h3><p>Let’s assume we have a Subject in AppService. Two different component (AComponent, BComonent) subscribe that Subject to get the data. We don’t need to bother about the service, hence I am jumping a bit and going to include the component code directly.</p><p><strong>AComponent</strong></p><pre>export class AComponent implements OnInit {<br>    details: any;<br>    constructor(service: AppService) { }<br>    ngOnInit() {<br>        this.service.subject<br>            .subscribe((data) =&gt; {<br>                this.process(data);<br>            });<br>    }<br>    process(data): void {<br>        <em>// this method process and set the data</em><br>        const newData = data; <em>// assuming newData is processed data</em><br>        this.setData(newData);<br>    }<br>    setData(newData) {<br>        this.details = newData;<br>    }<br>}</pre><p>Inside ngOnInit(), AComponent subscribes the subject to get the data. Later it does some processing before setting the data in details object of that component.</p><p><strong>BComponent</strong></p><pre>export class BComponent implements OnInit {<br>    formControl = new FormControl();<br>    constructor(service: AppService) { }<br>    ngOnInit() {<br>        this.service.subject<br>            .subscribe((data) =&gt; {<br>                this.process(data);<br>            });<br>    }<br>    process(data): void {<br>        <em>// this method process and set the data</em><br>        const newData = data; // <em>assuming newData is processed data</em><br>        this.setData(newData);<br>    }<br>    setData(newData) {<br>        this.formControl.setValue(newData);<br>    }<br>}</pre><p>BComponent also subscribes the data, does the processing and sets the data in a form control of that component.</p><p>Now look closely, as this two component do the same thing, hence most of the codes are duplicate. The only contrast here is inside the setData() method. AComponent updates the details object and BComponent uses the data to update the form. Except this part, every line is same to same. But we don’t want to keep duplicate code in our codebase.</p><p>Here the question comes, can we get rid of the redundant code? yes, of course we can. But how?</p><h3>Solution</h3><p>“<strong>Service</strong>” is the word that instantly came to my mind. We can easily move the processing part to a separate service and reduce redundancy. But we still need the subscription part and this is redundant also.</p><p>So, now what? <br>what we can do is, if we can somehow place the duplicate code in a parent class, this redundancy issue can be resolved. Here comes “Component Inheritance”. Let’s jump into it.</p><p>First, we need to create a base class and move the common code there. Let’s name it BaseComponent.</p><pre>export class BaseComponent implements OnInit, OnDestroy {<br>    protected unsubscribe = new Subject();</pre><pre>    constructor(public service: AppService) { }<br>    ngOnInit() {<br>        this.service.subject<br>            .pipe(takeUntil(this.unsubscribe))<br>            .subscribe((value) =&gt; {<br>                console.log(&#39;BASE&#39; + value);<br>                this.process(value);<br>            })<br>    }</pre><pre>    process(data): void {<br>        <em>// this method do some processing and set the data</em><br>        const newData = data; <em>// assuming newData is processed data</em><br>        this.setData(newData);<br>    }</pre><pre>    setData(newData) {<br>        <em>// implementation is in child class, as they are different</em><br>    }</pre><pre>    ngOnDestroy(): void {<br>        this.unsubscribe.next();<br>        this.unsubscribe.complete();<br>    }<br>}</pre><p>All the necessary code now is in BaseComponent except for setData() function. Different component can use the data differently, right? Like, AComponent uses it to update its details object, on the other hand BComponent uses it to update the form. As the implementation differs, it should be inside child class (AComponent, BComponent).</p><p>We don’t update our child classes, (AComponent, BComponent) yet. Let’s update those.</p><p>Updated <strong>AComponent</strong></p><pre>export class AComponent extends BaseComponent {<br>    details: any;<br>    constructor(public service: AppService) {<br>        super(service);<br>    }</pre><pre>    setData(newData) {<br>        this.details = newData;<br>    }<br>}</pre><p>Updated <strong>BComponent</strong></p><pre>export class BComponent extends BaseComponent {<br>    form = new FormControl();<br>    constructor(public service: AppService) {<br>        super(service);<br>    }</pre><pre>    setData(newData) {<br>        this.form.setValue(newData);<br>    }<br>}</pre><p>Now the code is cleaner than the previous, isn’t it?</p><p>ngOnInit() implementation is removed from these child classes as it is not necessary here. But in real scenario, you may have some code in ngOnInit() of child component class also.</p><blockquote>If you include ngOnInit() in child class (AComponent/BComponent), you need to call <strong>super.ngOnInit()</strong> (like we did for constructor).</blockquote><p>Inside AComponent/BComponent,</p><pre>ngOnInit() {<br>    <strong>super.ngOnInit();<br>    </strong><em>// other code</em><br>}</pre><p>We keep the method body empty in parent class, so that we can call it from parent and override it in child class. It is just a hack to bypass the error (or else compiler shows — method does not exist).</p><p>I have created a repository that may help someone interested. You also can edit that on stackblitz. You will find it <a href="https://github.com/sadidkhan/angular-coponent-inheritance"><strong><em>here</em></strong></a><strong><em>.</em></strong></p><h3>Opinion</h3><p>I discussed this scenario with my team mates and some found this approach may introduce complexity over readability. On the contrary, there is no harm knowing and trying a different approach. So, before using this approach, you should consider the pros and cons.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=888c2a2d3b27" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>