<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Ram kumar Shrestha</title>
    <description>The latest articles on DEV Community by Ram kumar Shrestha (@rm_sh).</description>
    <link>https://dev.to/rm_sh</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F2117110%2Fd6a81a6f-c5ec-4990-84b0-3dc63009f7fa.png</url>
      <title>DEV Community: Ram kumar Shrestha</title>
      <link>https://dev.to/rm_sh</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/rm_sh"/>
    <language>en</language>
    <item>
      <title>[Boost]</title>
      <dc:creator>Ram kumar Shrestha</dc:creator>
      <pubDate>Tue, 11 Feb 2025 05:23:26 +0000</pubDate>
      <link>https://dev.to/rm_sh/-1i01</link>
      <guid>https://dev.to/rm_sh/-1i01</guid>
      <description>&lt;div class="ltag__link"&gt;
  &lt;a href="/rm_sh" class="ltag__link__link"&gt;
    &lt;div class="ltag__link__pic"&gt;
      &lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F2117110%2Fd6a81a6f-c5ec-4990-84b0-3dc63009f7fa.png" alt="rm_sh"&gt;
    &lt;/div&gt;
  &lt;/a&gt;
  &lt;a href="https://dev.to/rm_sh/typeorm-eager-dont-fall-for-it-omf" class="ltag__link__link"&gt;
    &lt;div class="ltag__link__content"&gt;
      &lt;h2&gt;TypeORM Eager - Don't fall for it&lt;/h2&gt;
      &lt;h3&gt;Ram kumar Shrestha ・ Feb 11&lt;/h3&gt;
      &lt;div class="ltag__link__taglist"&gt;
        &lt;span class="ltag__link__tag"&gt;#database&lt;/span&gt;
        &lt;span class="ltag__link__tag"&gt;#postgres&lt;/span&gt;
        &lt;span class="ltag__link__tag"&gt;#typeorm&lt;/span&gt;
        &lt;span class="ltag__link__tag"&gt;#pitfall&lt;/span&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/a&gt;
&lt;/div&gt;


</description>
      <category>database</category>
      <category>postgres</category>
      <category>typeorm</category>
      <category>pitfall</category>
    </item>
    <item>
      <title>TypeORM Eager - Don't fall for it</title>
      <dc:creator>Ram kumar Shrestha</dc:creator>
      <pubDate>Tue, 11 Feb 2025 05:23:16 +0000</pubDate>
      <link>https://dev.to/rm_sh/typeorm-eager-dont-fall-for-it-omf</link>
      <guid>https://dev.to/rm_sh/typeorm-eager-dont-fall-for-it-omf</guid>
      <description>&lt;p&gt;&lt;strong&gt;Typeorm&lt;/strong&gt; is very helpful tool when working with &lt;em&gt;PostgreSQL&lt;/em&gt;. It has many built in features to help the developers. Among all of those features &lt;em&gt;&lt;strong&gt;eager&lt;/strong&gt;&lt;/em&gt; is one of them.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;eager&lt;/strong&gt;&lt;/em&gt; relations are loaded automatically each time you load entities from the database. For example, when &lt;strong&gt;Test&lt;/strong&gt; is loaded the items table will be automatically joined and populated.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Entity()
export class Test{
   @PrimaryGeneratedColumn('uuid')
   id: string;

   @OneToMany(() =&amp;gt; TestItem, (item) =&amp;gt; item.test, { eager: true })
   items: Array&amp;lt;TestItem&amp;gt;;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It seems fun only if it is totally independent from other entities. But when the &lt;strong&gt;Test&lt;/strong&gt; entity itself is joined to other entities then problem occurs.&lt;/p&gt;

&lt;p&gt;Here are few downfall of using &lt;em&gt;eager&lt;/em&gt;:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Memory overload when the &lt;strong&gt;Test&lt;/strong&gt; has too many items&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;As earlier said if its joint in other tables/entities where items is not needed, then in that case we can not disable eager loading of items which is redundant.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;It always makes sures to load &lt;em&gt;items&lt;/em&gt; or (eager loaded other relation) even for simple queries.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Performance issue as the &lt;em&gt;eager&lt;/em&gt; always loads all linked relations.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Might cause maximum call stack memory exceeded error.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Developers might forget the &lt;em&gt;eager&lt;/em&gt; has been used and use extra relations on &lt;strong&gt;typeorm&lt;/strong&gt; query or join table on query builder. &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Might go to infinite circular dependencies as below:&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Entity()
class TestItem {
   @ManyToOne(() =&amp;gt; Test, (test) =&amp;gt; test.items, { eager: true })
   test: Test;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here &lt;em&gt;Test&lt;/em&gt; tries to eager load &lt;em&gt;TestItem&lt;/em&gt; and vice versa which will cause circular dependencies.&lt;/p&gt;

&lt;h2&gt;
  
  
  Solution
&lt;/h2&gt;

&lt;p&gt;Only load the relations whenever needed as:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Use relations with typeorm
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;await Test.find({ 
  relations: ['items']
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Use join with query builder
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;await Test.createQueryBuilder('test')
         .leftJoinAndSelect('test.items', 'items')
         .getMany();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Have you ever used &lt;em&gt;eager&lt;/em&gt; and forgot that you have used and just go with relations causing eventually the tragedy of performance loading???&lt;/p&gt;

</description>
      <category>database</category>
      <category>postgres</category>
      <category>typeorm</category>
      <category>pitfall</category>
    </item>
    <item>
      <title>What is this?</title>
      <dc:creator>Ram kumar Shrestha</dc:creator>
      <pubDate>Sat, 08 Feb 2025 03:04:30 +0000</pubDate>
      <link>https://dev.to/rm_sh/-5e89</link>
      <guid>https://dev.to/rm_sh/-5e89</guid>
      <description>&lt;div class="ltag__link"&gt;
  &lt;a href="/rm_sh" class="ltag__link__link"&gt;
    &lt;div class="ltag__link__pic"&gt;
      &lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F2117110%2Fd6a81a6f-c5ec-4990-84b0-3dc63009f7fa.png" alt="rm_sh"&gt;
    &lt;/div&gt;
  &lt;/a&gt;
  &lt;a href="https://dev.to/rm_sh/what-is-this--1298" class="ltag__link__link"&gt;
    &lt;div class="ltag__link__content"&gt;
      &lt;h2&gt;What is THIS ?&lt;/h2&gt;
      &lt;h3&gt;Ram kumar Shrestha ・ Feb 8&lt;/h3&gt;
      &lt;div class="ltag__link__taglist"&gt;
        &lt;span class="ltag__link__tag"&gt;#javascript&lt;/span&gt;
        &lt;span class="ltag__link__tag"&gt;#frontend&lt;/span&gt;
        &lt;span class="ltag__link__tag"&gt;#programming&lt;/span&gt;
        &lt;span class="ltag__link__tag"&gt;#interviewtips&lt;/span&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/a&gt;
&lt;/div&gt;


</description>
      <category>javascript</category>
      <category>frontend</category>
      <category>programming</category>
      <category>interviewtips</category>
    </item>
    <item>
      <title>What is THIS ?</title>
      <dc:creator>Ram kumar Shrestha</dc:creator>
      <pubDate>Sat, 08 Feb 2025 02:57:02 +0000</pubDate>
      <link>https://dev.to/rm_sh/what-is-this--1298</link>
      <guid>https://dev.to/rm_sh/what-is-this--1298</guid>
      <description>&lt;p&gt;JavaScript the most popular programming language in the world. Almost every developer has been using JavaScript for various purposes from web app, mobile app, scripting to desktop app etc. JavaScript is so simple yet it can do almost everything. &lt;/p&gt;

&lt;p&gt;One of the most confusing topic ever in JavaScript is &lt;strong&gt;&lt;em&gt;this&lt;/em&gt;&lt;/strong&gt;. &lt;strong&gt;&lt;em&gt;this&lt;/em&gt;&lt;/strong&gt; keyword sound so simple but I found many developers confused while using it.&lt;/p&gt;

&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;blockquote&gt;
&lt;p&gt;The this keyword refers to the context where a piece of code, such as a function's body, is supposed to run.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;It severely depends on the runtime binding i.e, how its being invoked rather. Its value depends upon the context it appears.&lt;/p&gt;

&lt;h2&gt;
  
  
  Cases
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Global&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;When this is used standalone i.e, directly on the code not inside any scope then usually it gives the &lt;em&gt;global&lt;/em&gt; object (in non-strict mode) while its &lt;em&gt;undefined&lt;/em&gt; in strict mode.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Class&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If &lt;em&gt;this&lt;/em&gt; is inside the class context then its value will be the class instance itself whether its on constructor or in any methods.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class ThisCalss{
   name = "ThisClass"
    constructor() {
      console.log(this.name) // "ThisClass" upon instace creation
   }

   printName() {
       console.log(this.name) // "ThisClass upon method invocation
   }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Arrow Function&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Arrow functions' &lt;em&gt;this&lt;/em&gt; value depends on the enclosing &lt;em&gt;lexical context's this.&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const printName = () =&amp;gt; {
     console.log(this.name);
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Result : As the printName is directly under global lexical scope the console will print &lt;em&gt;undefined&lt;/em&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class ArrowExample {
  name = "ArrowExample";

  printName() {
    setTimeout(() =&amp;gt; {
      console.log(this.name);  
    }, 100);
  }
 }

 const arrow = new ArrowExample();
 arrow.printName();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Result: Here arrow function lexical scope is &lt;em&gt;ArrowExample&lt;/em&gt; class so the output will be &lt;em&gt;ArrowExample (value of name)&lt;/em&gt;.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Conventional Function&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In conventional functions (functions declared with the function keyword), this is determined by how the function is called, not where it's defined. The value of this depends on the calling context.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; function showThis() {
   console.log(this);
 }

 // Called directly
 showThis(); // window (in non-strict mode) or undefined (in strict mode)

 // As an object method
 const obj = {
    name: 'Object',
    show: showThis
 };
 obj.show(); // {name: 'Object', show: ƒ}

 // Using new keyword
 new showThis(); // showThis {}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Object&lt;/strong&gt;
Inside object's method the &lt;em&gt;this&lt;/em&gt; value is object itself.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; const laptop = {
     brand: 'Apple',
     getBrand: function() {
         return this.brand;
     }   
 }
console.log(laptop.getBrand()) // 'Apple'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Passing &lt;em&gt;this&lt;/em&gt; context
&lt;/h2&gt;

&lt;p&gt;We can control the &lt;em&gt;this&lt;/em&gt; context value with the help of &lt;em&gt;bind, apply, call.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;The &lt;em&gt;bind, call&lt;/em&gt; directly invokes methods/functions with the this context value. The only difference between them is the second parameters. &lt;em&gt;apply&lt;/em&gt; accepts comma separated value while &lt;em&gt;call&lt;/em&gt; accepts the array in second parameter.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; function getThis() {
   return this;
 }   

 console.log(getThis.apply('this apply')) // 'this apply'

 console.log(getThis.call('this apply 2'))  // 'this apply 2'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;While &lt;em&gt;bind&lt;/em&gt; will only create new reference of the function/method it will not be invoked. This &lt;em&gt;bind&lt;/em&gt; is very helpful iff we have to pass the function as parameter to any other function/methods.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; function getThis() {
     return this;
 }   

 const newRef = getThis.bind('this bind');
 console.log(getThis()); // undefined
 console.log(newRef()); // this bind
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Understanding this in JavaScript requires careful attention to the context in which it's used. Here are the key points to remember:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The value of this is determined by how a function is called (runtime binding)&lt;/li&gt;
&lt;li&gt;Class methods and object methods naturally bind this to their instance/object&lt;/li&gt;
&lt;li&gt;Arrow functions inherit this from their enclosing scope&lt;/li&gt;
&lt;li&gt;Conventional functions can have different this values based on their calling context&lt;/li&gt;
&lt;li&gt;bind, call, and apply provide ways to explicitly control this binding&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Being mindful of these rules will help you avoid common pitfalls and use this effectively in your JavaScript code.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>frontend</category>
      <category>programming</category>
      <category>interviewtips</category>
    </item>
    <item>
      <title>PostgreSQL Sorting - Not Simple as "You would think"</title>
      <dc:creator>Ram kumar Shrestha</dc:creator>
      <pubDate>Sat, 01 Feb 2025 02:13:51 +0000</pubDate>
      <link>https://dev.to/rm_sh/postgresql-sorting-not-simple-as-you-would-think-3odl</link>
      <guid>https://dev.to/rm_sh/postgresql-sorting-not-simple-as-you-would-think-3odl</guid>
      <description>&lt;p&gt;Accessing database collections and displaying the result is a peace of cake with various techniques. Users often need to sort the data according to their different need (for e.g. date). For that purpose &lt;em&gt;&lt;strong&gt;PostgreSQL's&lt;/strong&gt;&lt;/em&gt; default sort works as expected. However, when user attempts to sort the column that has numbers stored as string then things go wrong, the default sort gives unexpected results due to &lt;em&gt;&lt;strong&gt;lexicographical sorting&lt;/strong&gt;&lt;/em&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Lexicographical Order
&lt;/h2&gt;

&lt;blockquote&gt;
&lt;p&gt;The way data (like strings or numbers) is sorted in a "dictionary order," meaning characters are compared one by one, from left to right, just like how words are arranged in a dictionary, with the first character determining the order if the initial characters are the same.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Simply put &lt;strong&gt;&lt;em&gt;PostgreSQL&lt;/em&gt;&lt;/strong&gt; compares the words/values, stored as string (whether it is number or actual string) of the columns, from left to right based on their &lt;strong&gt;ASCII&lt;/strong&gt; code or &lt;strong&gt;Unicode&lt;/strong&gt; values. However it works on normal cases for strings but it won't work as expected in case of the number as strings.&lt;/p&gt;

&lt;p&gt;It is a case-sensitive sorting algorithm. Uppercase letters are considered smaller than lowercase letters.&lt;/p&gt;

&lt;h2&gt;
  
  
  Example
&lt;/h2&gt;

&lt;p&gt;Consider a &lt;strong&gt;persons&lt;/strong&gt; table with a &lt;strong&gt;name&lt;/strong&gt; and &lt;strong&gt;age&lt;/strong&gt; column, where &lt;strong&gt;age&lt;/strong&gt; is stored as a string:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;name     | age
---------|---------
'ram'    | '16'
'hari'   | '7'
'sita'   | '20'
'rita'   | '1'
'ashok'  | '104'
'prabin' | '2'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT name FROM persons ORDER BY name ASC;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Result&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;'ashok'
'hari'
'prabin'
'ram'
'rita'
'sita'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Excellent the output is as expected, now lets' see an example for sorting of &lt;strong&gt;age&lt;/strong&gt; which is stored as string.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT age FROM persons ORDER BY age ASC;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Result&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;'1'
'104'
'16'
'2'
'20'
'7'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is not what user expected but the according to the default &lt;strong&gt;PostgreSQL's&lt;/strong&gt; behavior this is correct.&lt;/p&gt;

&lt;h2&gt;
  
  
  Solutions for Sorting of Numerical String
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Type Casting:&lt;/strong&gt;
Casting the value to numbers before sorting makes sure it sorts the numbers as numbers rather than sorting string.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT age FROM persons ORDER BY age::INTEGER ASC;

--or 

SELECT age FROM persons ORDER BY CAST(age AS INTEGER) ASC;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Result&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;'1'
'2'
'7'
'16'
'20'
'104'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is the correct result as user expected.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;✅ Ensures correct numerical order, fast execution.&lt;/li&gt;
&lt;li&gt;❌ Fails if non-numeric values exist.&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Zero Prefix Padding:&lt;/strong&gt;
As we know normally people lives for 100 to 125 years old at max so, what we need to do is make sure the age is always three digits. For that purpose we use 0s before the values if those are not 3digits. 
The values should be stored by padding already if not we can use following query to simulate padding.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- Here LPAD means left padding
SELECT age FROM persons ORDER BY LPAD(age, 3, '0') ASC;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Padding Preprocessed columns&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;'1'   → '001'
'2'   → '002'
'7'   → '007'
'16'  → '016'
'20'  → '020'
'104' → '104'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Result&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;'1'
'2'
'7'
'16'
'20'
'104'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;✅ Works with strings, maintains consistency &lt;/li&gt;
&lt;li&gt;❌ Needs proper length padding&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;However lexicographical ordering works for following purposes as normal without any thoughts.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;String sorting algorithms.&lt;/li&gt;
&lt;li&gt;Searching for words in dictionaries.&lt;/li&gt;
&lt;li&gt;Comparing filenames, usernames, or keys in databases.&lt;/li&gt;
&lt;li&gt;Competitive programming challenges requiring string comparisons.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Lexicographical ordering plays a crucial role in string sorting but can cause issues when dealing with numeric strings. While *&lt;em&gt;PostgreSQL’s *&lt;/em&gt; default behavior follows lexicographical order, proper handling of numeric strings requires explicit type casting or padding techniques. By understanding and applying these solutions, developers can ensure accurate and expected sorting behavior in their applications.&lt;/p&gt;

&lt;p&gt;Have you faced similar sorting challenges? Share your experiences in the comments!&lt;/p&gt;

</description>
      <category>postgressql</category>
      <category>database</category>
      <category>backend</category>
      <category>sorting</category>
    </item>
    <item>
      <title>Intersection Observer API: A Hidden Gem in JavaScript</title>
      <dc:creator>Ram kumar Shrestha</dc:creator>
      <pubDate>Sun, 19 Jan 2025 14:12:02 +0000</pubDate>
      <link>https://dev.to/rm_sh/intersection-observer-api-a-hidden-gem-in-javascript-3ha0</link>
      <guid>https://dev.to/rm_sh/intersection-observer-api-a-hidden-gem-in-javascript-3ha0</guid>
      <description>&lt;p&gt;Recently while exploring the frontend world, I came upon a interesting feature of JavaScript -&amp;gt; Intersection Observer. &lt;strong&gt;Intersection Observer API&lt;/strong&gt; is one of the most underutilized and unheard JavaScript's features.&lt;/p&gt;

&lt;h2&gt;
  
  
  Intro
&lt;/h2&gt;

&lt;blockquote&gt;
&lt;p&gt;The Intersection Observer API provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document's viewport.&lt;br&gt;
However its sounds complex but it provides a simple solution for the most general problem: knowing when an element becomes visible of invisible to the use.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  Why It Matters
&lt;/h2&gt;

&lt;p&gt;&lt;em&gt;scroll&lt;/em&gt; event was the go-to method for developers when it comes to determine whether an element is visible on screen. Developers often had to perform manual calculations optimizations to ensure performance remained optimal, especially when tracking several elements. This approach could become inefficient while tracking several elements as the browser repeatedly recalculated positions during scrolling.&lt;/p&gt;

&lt;h2&gt;
  
  
  How It Works
&lt;/h2&gt;

&lt;p&gt;The Intersection Observer basically revolves around three components:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Observer:&lt;/strong&gt; The _IntersectionObserver _object watches one or more elements.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Callback:&lt;/strong&gt; A function is triggered whenever the visibility of a target element changes.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Options:&lt;/strong&gt; Configuration parameters like &lt;em&gt;root&lt;/em&gt;, &lt;em&gt;rootMargin&lt;/em&gt;, and &lt;em&gt;threshold&lt;/em&gt;. &lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;em&gt;root&lt;/em&gt;: Defines viewport for checking visibility. The default value is null which refers to browser;s viewport.&lt;/li&gt;
&lt;li&gt;
&lt;em&gt;rootMargin&lt;/em&gt;: A margin around the root element, similar to &lt;strong&gt;CSS&lt;/strong&gt; margin. Positive value grows/adds while negative value shrinks/subtracts the bounding box of the root element.&lt;/li&gt;
&lt;li&gt;
&lt;em&gt;threshold&lt;/em&gt; :  Specifies the percentage of the target element’s visibility that must be reached before the observer’s callback is triggered. It ranges from 0 (0%) to 1 (100%)&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Implementation
&lt;/h2&gt;

&lt;p&gt;To get started, create an instance of  &lt;strong&gt;IntersectionObserver&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  const lazyObserver = new IntersectionObserver(handleLazyImage, {
    rootMargin: "-10px", //10px margin was used in the container to address that margin
    root: lazyImageContainer, // Custom container as the root
    threshold: 0.25, // Trigger when 10% of the image is visible in the container
  });

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the example above, &lt;strong&gt;handleLazyImage&lt;/strong&gt; is callback function while the remaining properties are config options.&lt;/p&gt;

&lt;p&gt;After the observer is instantiated, simply start observing the target elements:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  lazyImages.forEach((img) =&amp;gt; lazyObserver.observe(img));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For more details, you can checkout the&lt;a href="https://github.com/ram-kumar-shrestha/intersection-observable" rel="noopener noreferrer"&gt;Github repository&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Practical Use cases
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Infinite Scrolling&lt;/strong&gt;: Detect when the user reaches the end of the page and fetch new data via API calls.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Lazy Loading&lt;/strong&gt;: Load images or other content as they come into view during scrolling.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Ad Visibility Reporting&lt;/strong&gt;: Track whether advertisements are visible to users to calculate ad revenue.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Task and Animation Control&lt;/strong&gt;: Trigger tasks or animations only when the user is likely to see the results, improving performance and user experience.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;The Intersection Observer API represents a significant step forward in how we handle viewport-based interactions in web applications. It provides a clean, efficient solution for many common use cases while improving performance and reducing complexity. Whether you're implementing lazy loading, infinite scrolling, or scroll-based animations, the Intersection Observer API should be your go-to tool.&lt;/p&gt;

&lt;p&gt;Give it a try in your next project - your users (and your performance metrics) will thank you!&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>programming</category>
      <category>eagertolearn</category>
      <category>frontend</category>
    </item>
    <item>
      <title>Switching Modes: Implementing a Light-Dark Theme by CSS Only 🌗</title>
      <dc:creator>Ram kumar Shrestha</dc:creator>
      <pubDate>Fri, 22 Nov 2024 11:00:17 +0000</pubDate>
      <link>https://dev.to/rm_sh/switching-modes-implementing-a-light-dark-theme-by-css-only-1o9k</link>
      <guid>https://dev.to/rm_sh/switching-modes-implementing-a-light-dark-theme-by-css-only-1o9k</guid>
      <description>&lt;p&gt;Switching between light and dark themes has become a must-have feature for modern websites, as most users prefer having control over their viewing preferences. This small yet impactful addition can significantly enhance usability, aesthetics, and overall user experience.&lt;/p&gt;

&lt;p&gt;In this blog, we’ll explore how to implement a light-dark theme toggle using CSS and JavaScript, ensuring both accessibility and a seamless experience for your users.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why Light-Dark Themes?
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;User Preferences: Mos users prefer dark themes to reduce eye strain, especially in low-light environments.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Aesthetic Appeal: A well-designed dark theme adds a modern touch to your website.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Device Compatibility: Many devices now support dark mode natively, and websites can complement this feature.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  CSS's Powerful Light-Dark Property
&lt;/h2&gt;

&lt;p&gt;CSS introduced a powerful property &lt;strong&gt;&lt;em&gt;light-dark&lt;/em&gt;&lt;/strong&gt; to simplify theme toggling. In this blog, we’ll explore how to use it with a straightforward example.&lt;/p&gt;

&lt;h2&gt;
  
  
  Example
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Simple HTML structure
The first step is provide a button which will toggle the theme in the web browser.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;body id="content"&amp;gt;
  &amp;lt;button id="theme-toggle"&amp;gt;Switch Theme&amp;lt;/button&amp;gt;
&amp;lt;/body&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, clicking the button will toggle the theme.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Provide the CSS for theme toggle
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#content {
   background-color: light-dark(#eeee, #424242);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, #eee will be the background color for light theme and #424242 will be for the dark theme.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Script to toggle the theme
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const themeToggle = document.getElementById("theme-toggle");

themeToggle.addEventListener("click", () =&amp;gt; {
  const content = document.getElementById("content");
  const currentTheme = content.style["color-scheme"];

 content.style["color-scheme"] = currentTheme === "dark" ? "light" : "dark";
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When the &lt;strong&gt;&lt;em&gt;theme-toggle&lt;/em&gt;&lt;/strong&gt; button is clicked, the script toggles the theme between light and dark modes dynamically.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Implementing a light-dark theme toggle is an essential feature for enhancing user experience and aligning with modern design trends. By leveraging the power of CSS and JavaScript, you can create an accessible, visually appealing, and user-friendly theme toggle for your website.&lt;/p&gt;

&lt;p&gt;With this feature, you not only accommodate users’ preferences but also ensure compatibility with devices that support native dark modes. Adding a light-dark theme toggle is a small but meaningful step toward creating a more versatile and inclusive web experience.&lt;/p&gt;

</description>
      <category>css</category>
      <category>themes</category>
      <category>frontend</category>
      <category>learneveryday</category>
    </item>
    <item>
      <title>Why You Shouldn’t Use Libraries Blindly: A Lesson in Bundle Size</title>
      <dc:creator>Ram kumar Shrestha</dc:creator>
      <pubDate>Thu, 14 Nov 2024 10:08:12 +0000</pubDate>
      <link>https://dev.to/rm_sh/why-you-shouldnt-use-libraries-blindly-a-lesson-in-bundle-size-2dm4</link>
      <guid>https://dev.to/rm_sh/why-you-shouldnt-use-libraries-blindly-a-lesson-in-bundle-size-2dm4</guid>
      <description>&lt;p&gt;When developing any web applications, the instinctive choice is to reach for popular libraries that solve our specific problem quickly. However, while libraries can save time, it’s essential to carefully evaluate their impact on the final product. One often overlooked factor is bundle size, which can significantly affect your application’s performance, especially for end-users with limited internet speed.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Issue: Too Big Bundle Sizes
&lt;/h2&gt;

&lt;p&gt;Each third-party library you add to a project contributes to the overall size of your application’s bundle. Large bundles can slow down page load times, leading to poor user experience and lower SEO rankings. This issue becomes more evident when libraries include more functionality than you need. Initially, you may think what if our bundle size increases by just some MB. But, that will cost a lot in page load time.&lt;/p&gt;

&lt;h2&gt;
  
  
  Real-World Example: The country-state-city Library
&lt;/h2&gt;

&lt;p&gt;Let's say we’re building a simple form with dropdowns for selecting a user’s address. At first glance, &lt;strong&gt;&lt;em&gt;country-state-city&lt;/em&gt;&lt;/strong&gt; seems like an ideal choice — it’s popular, covers all the data you need, and is ready to go. However, on closer inspection, it brings along a hefty payload, as it includes an extensive database of countries, states, and cities worldwide all in frontend only.&lt;/p&gt;

&lt;p&gt;For instance:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Bundle Bloat: &lt;strong&gt;&lt;em&gt;country-state-city&lt;/em&gt;&lt;/strong&gt; brings all three datasets: countries, states, and cities, and with a great cost its about 10MB+ in size which will be much more big than app itself.&lt;/li&gt;
&lt;li&gt;Stale Data: While the &lt;em&gt;&lt;strong&gt;country-state-city&lt;/strong&gt;&lt;/em&gt; library offers a comprehensive dataset, it’s not always up-to-date. For example, in Nepal, administrative divisions have shifted from development regions to provinces. However, &lt;em&gt;&lt;strong&gt;country-state-city&lt;/strong&gt;&lt;/em&gt; still organizes Nepal’s data according to the outdated development regions. Relying on such a library can lead to inconsistencies, as users may encounter data that doesn’t align with current administrative structures.
Loading this extra data could negatively affect your app’s performance, and ultimately, the user experience.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  The Solution: Create a Custom API
&lt;/h2&gt;

&lt;p&gt;Instead of using a library that doesn't meet client's expectations, consider creating a custom API that serves the data your application requires. In this example, building a backend API for this will completely remove the oversized library. Here are a few reasons why:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Reduced Bundle Size: Custom APIs removes the oversized library form frontend totally, reducing load times and improving responsiveness.&lt;/li&gt;
&lt;li&gt;Better Performance: Custom APIs offer faster response times because they process smaller requests and return only the required information.&lt;/li&gt;
&lt;li&gt;Enhanced Control: With a custom API, you’re in control of the data’s structure and format, allowing you to modify it as your app evolves.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Steps to Build Your Own API for Country and State Data
&lt;/h2&gt;

&lt;p&gt;Here’s a quick outline for building your own API:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Define the Requirements:&lt;/strong&gt; Identify the data scope—perhaps only a limited set of countries and states, the &lt;em&gt;&lt;strong&gt;country-state-city&lt;/strong&gt;&lt;/em&gt; itself can be used as great inspiration and reference.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Data Source:&lt;/strong&gt; Use a reliable open-source dataset or an external API to populate your database.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Build the API:&lt;/strong&gt; Create a simple REST API endpoint to serve this data.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Optimize for Performance:&lt;/strong&gt; Cache frequently requested data and use efficient database queries.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Integrate with the App:&lt;/strong&gt; Fetch only the data you need from this custom API, rather than an entire library.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Key Takeaway: Assess Before You Install
&lt;/h2&gt;

&lt;p&gt;While it can be tempting to use libraries for their convenience, it’s essential to consider the implications carefully:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Evaluate Bundle Impact: Before adding a library, check the impact on bundle size.&lt;/li&gt;
&lt;li&gt;Consider Long-Term Maintenance: Additional libraries introduce dependencies, which require updates and maintenance.&lt;/li&gt;
&lt;li&gt;Check for Unused Features: Look for ways to use only the parts you need or alternatives to avoid excess data.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;By taking the time to assess each library and evaluating alternative solutions like custom APIs, you can improve performance and ensure your app remains light and user-friendly. Libraries can be great tools, but they aren’t a one-size-fits-all solution—use them wisely to strike the right balance between convenience and efficiency.&lt;/p&gt;

</description>
      <category>react</category>
      <category>frontend</category>
      <category>softwareengineering</category>
      <category>learning</category>
    </item>
    <item>
      <title>💡 Database Development: It’s Not Just About Querying!</title>
      <dc:creator>Ram kumar Shrestha</dc:creator>
      <pubDate>Tue, 12 Nov 2024 12:12:18 +0000</pubDate>
      <link>https://dev.to/rm_sh/database-development-its-not-just-about-querying-4lap</link>
      <guid>https://dev.to/rm_sh/database-development-its-not-just-about-querying-4lap</guid>
      <description>&lt;p&gt;As backend/database engineers, we often think of databases as places to store and retrieve data. But sometimes, with a bit of exploration, we realize they can do much more.&lt;/p&gt;

&lt;p&gt;Recently, I faced a unique requirement in my project with PostgreSQL: after inserting a row into &lt;strong&gt;&lt;em&gt;public.test_table&lt;/em&gt;&lt;/strong&gt;, every existing row in that same table needed to be updated to reflect the new information.&lt;/p&gt;

&lt;h2&gt;
  
  
  Initial Approach
&lt;/h2&gt;

&lt;p&gt;At first, my instinct was to handle this logic in the backend, creating a method in the NestJS service layer to process each row update. But then I paused and thought: could PostgreSQL handle this independently?&lt;/p&gt;

&lt;p&gt;A bit of research later, I found the answer: Yes, with triggers! By leveraging PostgreSQL triggers and functions, we can move this logic directly to the database, improving both performance and maintainability.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Solution: PostgreSQL Trigger and Function
&lt;/h2&gt;

&lt;p&gt;Using a trigger to automate updates means that every time a row is inserted, PostgreSQL takes over and runs the update logic on all rows.&lt;/p&gt;

&lt;p&gt;Here’s the process:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Define a function&lt;/strong&gt; in PostgreSQL to specify the logic applied to all rows.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Create a trigger&lt;/strong&gt; that executes this function after every insert on public.test_table.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Example Code
&lt;/h2&gt;

&lt;p&gt;Here’s a simplified example of what this looks like in PostgreSQL :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- Step 1: Create a function that updates all rows in the table
CREATE OR REPLACE FUNCTION update_all_rows() 
RETURNS TRIGGER AS $$
BEGIN
    -- Custom logic applied to all rows; here’s a simple example
    UPDATE public.test_table
    SET column_name = NEW.column_name;
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

-- Step 2: Create a trigger that calls the function after every insert
CREATE TRIGGER after_insert_trigger
AFTER INSERT ON public.test_table
FOR EACH ROW EXECUTE FUNCTION update_all_rows();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Including in a Migration File
&lt;/h2&gt;

&lt;p&gt;For consistency across environments, adding this code to a migration file ensures it is applied automatically in each deployment. Here’s a sample migration file using TypeORM:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { MigrationInterface, QueryRunner } from "typeorm";

export class AddUpdateAllRowsTriggerToTestTable implements MigrationInterface {
    public async up(queryRunner: QueryRunner): Promise&amp;lt;void&amp;gt; {
        await queryRunner.query(`
            CREATE OR REPLACE FUNCTION update_all_rows() 
            RETURNS TRIGGER AS $$
            BEGIN
                UPDATE public.test_table
                SET column_name = NEW.column_name;
                RETURN NEW;
            END;
            $$ LANGUAGE plpgsql;

            CREATE TRIGGER after_insert_trigger
            AFTER INSERT ON public.test_table
            FOR EACH ROW EXECUTE FUNCTION update_all_rows();
        `);
    }

    public async down(queryRunner: QueryRunner): Promise&amp;lt;void&amp;gt; {
        await queryRunner.query(`
            DROP TRIGGER IF EXISTS after_insert_trigger ON public.test_table;
            DROP FUNCTION IF EXISTS update_all_rows;
        `);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Key Benefits
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Efficiency:&lt;/strong&gt; Processing the logic directly within the database reduces network load and speeds up data handling.&lt;br&gt;
&lt;strong&gt;Maintainability:&lt;/strong&gt; Centralizing logic in the database means fewer lines of application code and a more maintainable backend.&lt;br&gt;
&lt;strong&gt;Portability:&lt;/strong&gt; Using a migration file ensures that this functionality is automatically set up in every environment.&lt;/p&gt;

&lt;h2&gt;
  
  
  Takeaway
&lt;/h2&gt;

&lt;p&gt;This experience was a reminder of the untapped capabilities in PostgreSQL and the benefits of letting the database handle certain logic independently.&lt;/p&gt;

&lt;p&gt;🚀 Have you ever found a creative solution by using database features to streamline your code? Let's share insights and learn from each other!&lt;/p&gt;

</description>
      <category>database</category>
      <category>postgressql</category>
      <category>backend</category>
      <category>softwareengineering</category>
    </item>
    <item>
      <title>Optimizing Error Handling: Reducing Redundant Try-Catch Blocks</title>
      <dc:creator>Ram kumar Shrestha</dc:creator>
      <pubDate>Tue, 24 Sep 2024 07:35:06 +0000</pubDate>
      <link>https://dev.to/rm_sh/optimizing-error-handling-reducing-redundant-try-catch-blocks-4e2c</link>
      <guid>https://dev.to/rm_sh/optimizing-error-handling-reducing-redundant-try-catch-blocks-4e2c</guid>
      <description>&lt;p&gt;In any application, error handling is critical to maintain stability and reliability. Typically, a common way to handle errors is by using try-catch blocks. While effective, this approach can clutter the code, make it less DRY, decrease readability, and complicate maintenance.&lt;/p&gt;

&lt;p&gt;In this post, we will explore a more efficient way to handle errors in a TypeScript OOP-based application using NestJS by leveraging decorators.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Problem with try-catch Blocks
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Code Duplication:&lt;/strong&gt; As the number of methods increases in a class, duplicating the same try-catch blocks across various methods becomes inefficient and harder to manage.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Reduced Readability:&lt;/strong&gt; Nesting try-catch blocks leads to nested code blocks, which can make the code more difficult to read and understand.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Poor Exception Propagation:&lt;/strong&gt; If exceptions are caught too early, they may not propagate to higher layers of the application where they can be handled more appropriately, missing opportunities for centralized error handling.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  The Solution: Using Decorators for Error Handling
&lt;/h2&gt;

&lt;p&gt;Instead of repeating try-catch blocks, we can centralize error handling using decorators. This approach keeps the code cleaner, more readable, and easier to maintain.&lt;/p&gt;

&lt;p&gt;In NestJS, we can use decorators to intercept method calls and handle errors globally across services. Let's see how we can achieve this.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1:&lt;/strong&gt; Defining the Error Handling Decorator&lt;br&gt;
Here's how we can create a decorator to handle errors in methods:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F038oqd2um9uuhzoe2eu9.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F038oqd2um9uuhzoe2eu9.png" alt="Decorator" width="" height=""&gt;&lt;/a&gt;&lt;br&gt;
This decorator wraps the method execution in a try-catch block.&lt;br&gt;
Any error caught is logged, and an RpcException is thrown to signal an error in a gRPC-based service.&lt;br&gt;
&lt;em&gt;Note: This example uses RpcException, which is specific to gRPC microservices. If you're not using gRPC, you can replace it with an appropriate exception type (e.g., HttpException for HTTP-based services).&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 2:&lt;/strong&gt; Using the Decorator in Services&lt;br&gt;
Once the decorator is defined, you can apply it to any service method that needs centralized error handling:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F201v41iaf1og92eyzmep.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F201v41iaf1og92eyzmep.png" alt="Use case" width="" height=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;By adding @HandleErrors() above a method, you ensure that any error occurring within that method will be caught by the decorator and handled appropriately.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;By adopting decorators for error handling, you can reduce the number of redundant try-catch blocks in your code, making it cleaner, more readable, and easier to maintain.&lt;/p&gt;

&lt;p&gt;Centralizing error handling through decorators helps you:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Keep your code DRY (Don't Repeat Yourself).&lt;/li&gt;
&lt;li&gt;Handle exceptions more systematically.&lt;/li&gt;
&lt;li&gt;Improve readability and reduce clutter in methods.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In summary, this approach allows you to manage errors more efficiently by handling them at the right level and letting exceptions propagate when necessary. This makes debugging and maintaining your code much simpler.&lt;/p&gt;

</description>
    </item>
  </channel>
</rss>
