<?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: Soumya Rauth</title>
    <description>The latest articles on DEV Community by Soumya Rauth (@soumyarauth).</description>
    <link>https://dev.to/soumyarauth</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%2F563447%2F269d5907-b086-4a3c-be29-a2ab62737081.jpeg</url>
      <title>DEV Community: Soumya Rauth</title>
      <link>https://dev.to/soumyarauth</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/soumyarauth"/>
    <language>en</language>
    <item>
      <title>Have you considered using Object Literals in typescript as a replacement for the If..Else or Switch..Case.. ?</title>
      <dc:creator>Soumya Rauth</dc:creator>
      <pubDate>Thu, 21 Nov 2024 20:20:59 +0000</pubDate>
      <link>https://dev.to/soumyarauth/have-you-considered-using-object-literals-in-typescript-as-a-replacement-for-the-ifelse-or-2i8e</link>
      <guid>https://dev.to/soumyarauth/have-you-considered-using-object-literals-in-typescript-as-a-replacement-for-the-ifelse-or-2i8e</guid>
      <description>&lt;p&gt;&lt;a href="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%2Farticles%2Fcec6p4wxl8bo8skk0ztf.jpg" class="article-body-image-wrapper"&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%2Farticles%2Fcec6p4wxl8bo8skk0ztf.jpg" alt="Image description" width="800" height="533"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Using If Else is a super essential. But there are times when if becomes less readable and hard to scale as the number of conditions increase. As a replacement, we tend to use Switch Cases. But, with the inception of typescript the chances to write cleaner and readable code has shifted to another level. At least I find it more readable ( Maybe this is opinionated..Feel free to present your views on this ).&lt;/p&gt;

&lt;p&gt;Now, let’s get straight to the heart of this article. Let me show you an implementation of a piece of code in three different versions.&lt;/p&gt;

&lt;p&gt;Basically, this code transforms any sentence into different cases ( smallcase, uppercase, titlecase etc ).&lt;/p&gt;

&lt;h2&gt;
  
  
  Version — 1 ( If..Else.. )
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export const transformCase = ({ text, format }: TransformCaseTypeProps) =&amp;gt; {
  if (format === "small") { //smallcase
    return text.toLocaleLowerCase();
  } else if (format === "title") { //titlecase
    return text
      .split(" ")
      .map(
        (word) =&amp;gt; word.toLowerCase().charAt(0).toUpperCase() + word.slice(1)
      )
      .join(" ");
  } else if (format === "upper") { //uppercase
    return text.toUpperCase();
  } else {
    return text; // default case
  }
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This if…else code will work just fine. Also, I am not saying that using this isn’t a valid choice. But, there is also a better way with less code and a cleaner layout. Moreover, there are ways to stop the repetition of code ( like in here the if..else will just tend to increase in numbers as the conditions grow ).&lt;/p&gt;

&lt;h2&gt;
  
  
  Version — 2 ( Switch..Case.. )
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export const transformCase = ({ text, format }: TransformCaseTypeProps) =&amp;gt; {
  switch (format) {
    case "small": // smallcase
      return text.toLocaleLowerCase();
    case "title": // titlecase
      return text
        .split(" ")
        .map(
          (word) =&amp;gt; word.toLowerCase().charAt(0).toUpperCase() + word.slice(1)
        )
        .join(" ");
    case "upper": // uppercase
      return text.toUpperCase();
    default: // default case
      return text;
  }
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This version with the switch case can surely be considered a bit cleaner because of group related cases in a structured and organized format, making it easier to follow the logic for multiple conditions in a better way. Additionally, it is easy to add new cases ( just add a new case block ) comparing to the if..else version. Nevertheless, this still requires multiple case ( repetition of code ) statements, as well as, explicit return for each case. All these making it harder to focus on the core functionality.&lt;/p&gt;

&lt;h2&gt;
  
  
  Version — 3 ( Object Literal )
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export const transformCase = ({ text, caseName }: TransformCaseTypeProps) =&amp;gt; {
  const formatters = {
    small: () =&amp;gt; text.toLocaleLowerCase(), //smallcase
    title: () =&amp;gt;                           //titlecase
      text
        .split(" ")
        .map(
          (word) =&amp;gt; word.toLowerCase().charAt(0).toUpperCase() + word.slice(1)
        )
        .join(" "),
    upper: () =&amp;gt; text.toUpperCase(),        //uppercase
    default: () =&amp;gt; text,
  };

  const transform = formatters[caseName];
  if (!transform) {
    throw new Error(
      `Invalid format: "${caseName}". Allowed formats are: ${Object.keys(
        formatters
      ).join(", ")}`
    );
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, this is my suggested approach. Following are the key points based on my point of views —&lt;/p&gt;

&lt;h3&gt;
  
  
  Separation of Concerns
&lt;/h3&gt;

&lt;p&gt;Each cases (small, title, upper, etc.) is encapsulated in its own function within the object, demonstrating the separation of concern.&lt;/p&gt;

&lt;h3&gt;
  
  
  Extensibility
&lt;/h3&gt;

&lt;p&gt;Adding new cases is as simple as appending a new key-value pair in the object. Each new case is self-contained and doesn’t require modifying control flow logic where on the other versions, adding a new case would mean to repeat the a block ( new if..else OR new switch..case .. ), increasing code complexity as more cases are added. On top of that, this is cleaner, minimal, and better structured.&lt;/p&gt;

&lt;p&gt;Hope you will be able to find more better aspects of this approach or maybe an entire way which is better. Feel free to share your thoughts. Ciao!&lt;/p&gt;

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