<?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 Ashan Perera on Medium]]></title>
        <description><![CDATA[Stories by Ashan Perera on Medium]]></description>
        <link>https://medium.com/@ashantiwankaperera?source=rss-215563e04d5a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*7UXmiJR4yD0XanbzrXOwbw.jpeg</url>
            <title>Stories by Ashan Perera on Medium</title>
            <link>https://medium.com/@ashantiwankaperera?source=rss-215563e04d5a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 16:17:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ashantiwankaperera/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[Why I Stripped My UI Library to Build a High-Performance Component]]></title>
            <link>https://medium.com/pickme-engineering-blog/why-i-stripped-my-ui-library-to-build-a-high-performance-component-733311ec91b6?source=rss-215563e04d5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/733311ec91b6</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Ashan Perera]]></dc:creator>
            <pubDate>Fri, 13 Mar 2026 06:54:16 GMT</pubDate>
            <atom:updated>2026-03-13T06:54:16.448Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G_Tvs7KI2SPRKd43W8I9EQ.gif" /></figure><p>It started as a routine task. Build a reusable, editable table for our internal component library. The requirements were clear: handle 10+ columns, 1,000+ rows of CSV data with real-time, cross-row, and cross-column validation. If a value in Row 1 conflicted with a value in Row 999, the UI needed to show an error in the cell immediately.</p><p>We had already chosen the industry-standard <strong>Ant Design </strong>as our UI library for the in-house common component library. It’s robust, aesthetic, and already baked into our design system. I thought I was being efficient. Instead, I was walking straight into a performance wall.</p><h4>The Illusion of the “Standard” Way</h4><p>My initial architecture was the “textbook” approach:</p><ul><li><strong>Papa Parse</strong> for CSV processing.</li><li><strong>AntD Table</strong> for the layout.</li><li><strong>AntD Form</strong> to manage the editable fields and validation rules.</li></ul><p>At 10 or 25 rows per page, the implementation was flawless. But when I toggled the pagination to <strong>100 rows</strong>, the <strong>“LAG”</strong> appeared.</p><h4>The 100-Row Wall</h4><p>Typing a single character into a cell resulted in a few-second delay. The UI didn’t just stutter; it froze.</p><p>The React Profiler was red. The issue wasn’t just my validation logic; it was the <strong>reconciliation</strong>. Because every cell was part of a centralized AntD Form, a single keystroke in a row forced React to “check” the entire tree. Even with memoization, the overhead of the Virtual DOM diffing was enough to lock the main thread.</p><p>If you want to read more about memoization, here is an article below.</p><p><a href="https://medium.com/@ashantiwankaperera/end-of-memorization-with-react-19-react-memo-usecallback-usememo-b8df7f18aba1">End of Memoization with React 19? (React.memo, useCallback, useMemo)</a></p><p>I was facing a fundamental architectural limitation of AntD, which is designed for <strong>record-scale</strong> entry, not <strong>grid-scale</strong> data processing.</p><h3>The Optimization Trap</h3><p>Before admitting that the architecture was the problem, I tried every optimization in the book. I began a journey of trying to “hack” performance into a stack that wasn’t built for it. I was determined to stay within the AntD ecosystem, but every change I made felt like making it worse or leaving it the same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*FxdP6thKz7R4FNtx.gif" /></figure><h4>1. The AntD EditableProTable</h4><p>My first move was to look into the community and the docs. After hours of documentation reading and going through various GitHub issues and forms, many had suggested AntD <strong>EditableProTable</strong>. So I switched to that.</p><p>On paper, it was the perfect candidate. A specialized component designed exactly for CRUD operations. It wasn&#39;t giving the expected results. Because it relied on the same centralized Form Context, the internal “bookkeeping” required was just as heavy. Virtualization solved the DOM rendering, but it couldn’t solve the <strong>Scripting Bottleneck</strong>. The browser was struggling just to calculate which parts of the state had changed.</p><p>Following is a mock app created using AntD EditableProTable.</p><p><a href="https://antd-rhf-table-problem.netlify.app/#editable">antd-rhf-table</a></p><h4>2. The Decoupling</h4><p>Next, I attempted to strip away the controlled nature of AntD by integrating <strong>React Hook Form (RHF)</strong>. My logic was sound: RHF uses refs to avoid global re-renders, which should isolate the “typing” from the rest of the table. It worked partially. While the typing lag decreased, the Cross-Row Validation became my new problem. Because my validation was real-time, every single character typed had to be checked against a dependency graph of all other rows.</p><p>This got me thinking that maybe letting the main thread do everything might be the issue here. Is there a way to offload some of the heavy lifting from the main thread?</p><h4>3. The Web Worker</h4><p>To free up the main thread, I moved the entire validation engine to a <strong>Web Worker</strong>. I felt like the solution for a moment. I had finally offloaded the heavy O(n) calculations to a separate CPU core. Typing was finally fast.</p><p>I realized I had traded <strong>Technical Lag</strong> for <strong>UX Friction</strong>. Because the communication between the UI and the Worker was asynchronous, the user was faster than the validation. To maintain data integrity, I implemented a queue system that blocked certain actions while the Worker validated. Even though the browser didn’t freeze, the user flow did. My lead approved this workaround, and the business was satisfied, but I knew it wasn’t right. It was a functional solution that lacked the robustness and smoothness of a professional tool.</p><p>Below is an article I wrote about this while working on it.</p><p><a href="https://medium.com/@ashantiwankaperera/web-workers-the-secret-to-a-smooth-fast-frontend-a8c30405fb88">Web Workers: The Secret to a Smooth, Fast Frontend</a></p><p>This brought me to the lowest point. I had a working solution with Web Workers that passed testing and all, but the UX felt like a compromise. I couldn’t shake the feeling that I was over-engineering a workaround for a problem that shouldn’t exist.</p><p>That’s when I decided to look backward.</p><h3>The Legacy Angular</h3><p>Our company had a legacy internal tool, an old codebase built with <strong>Angular</strong> and <strong>MUI</strong>. It performed a similar task. There was a senior engineer who had worked on that codebase in our team. Out of curiosity, we fired it up and started testing. It was instant, no lag, no validation queues, no asynchronous pop-ins.</p><p><strong>How could an “old” stack outperform my modern React app?</strong></p><p>I realized the bottleneck was the<strong> </strong>efficiency itself. React is designed for “Tree-Walking”. When data changes, it re-evaluates the tree to decide what to update. Angular’s more fine-grained approach didn’t “think” about the tree; it just updated the specific DOM node. In a massive table, React was spending all its resources and time <strong>calculating</strong> the change, while the legacy app was just <strong>making</strong> the change.</p><p>Following is an mocl POC I did of this implementation.</p><p><a href="https://antd-rhf-table-problem.netlify.app/#raw">antd-rhf-table</a></p><h4>Going Old School</h4><p>I realized that to achieve the performance I needed, I had to stop being <strong>“Declarative”</strong> and start being <strong>“Imperative”.</strong> I needed to tell the browser exactly what to do, rather than asking React to figure it out for me.</p><p>So I stripped out every useState and useEffect from the table cells and replaced them with <strong>useRefs</strong>. By holding the data in a plain JavaScript object inside a Ref, I bypassed React’s state-management engine entirely. When a user interacted with the table, I didn’t trigger a re-render. I manually reached into the DOM to run validations and update values.</p><p><strong>To my surprise, the performance jumped immediately!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/0*dSWJElAL9SwGzNgr.gif" /></figure><p>But I wasn’t done. Even without state updates, the <strong>Ant Design</strong> components in each cell carried their own internal logic and listeners. I had to getrid of that overhead as well.</p><h3>The Final Shot</h3><p>I was at a crossroads: keep the “standard” look and the lag, or delete the library and build the engine the project actually needed. The choice was obvious. I stripped out every AntD component — both the Table and the Form.</p><p>I wrote a pure TypeScript table with HTML and CSS to match the AntD table aesthetic, ensuring our design system’s integrity remained intact.</p><p>I replaced the heavy Form Context with a single massive Reducer function.</p><h4>One Big Reducer</h4><p>Instead of lots of independent functions trying to talk to each other, I created a single, centralized “Source of Truth.”</p><ul><li><strong>The Keystroke:</strong> A single action is dispatched to the Reducer.</li><li><strong>The Processing:</strong> The Reducer runs the entire table row validation suite as a pure JavaScript operation for O(1) lookups.</li><li><strong>The Render:</strong> The UI reflects the results instantly.</li></ul><p><strong>To my surprise, this was the fastest!</strong></p><p>By removing the UI library, the entire validation suite finished right on the main thread. It was faster than the Web Worker, faster than the legacy app, and finally met the performance I was hoping for.</p><p>After reviewing with my lead, this was the version that went to production.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/0*eJ8v25JJwoyYICTC.gif" /></figure><p>Looking back, the business was already satisfied with my Web Worker workaround. But I couldn’t ignore the feeling that I hadn’t built the best solution.</p><blockquote>My CTO once quoted Larry Page: <strong>“Always work hard on something uncomfortably exciting!”</strong></blockquote><p>This experience was exactly that.</p><p>Still, even after all this work, I might be completely wrong. Perhaps there is a better workaround I missed, or maybe I&#39;m stupid enough to overlook a fundamental basic at the very beginning that could have prevented the issue in the first place.</p><p>So to my fellow developers, please feel free to correct me or share if you have encountered a similar experience. You can find all the mock code and testing I did in the following repo.</p><p><a href="https://github.com/AshanPerera98/antd-rhf-table-problem">GitHub - AshanPerera98/antd-rhf-table-problem</a></p><p>As always, <strong>Happy Coding!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=733311ec91b6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pickme-engineering-blog/why-i-stripped-my-ui-library-to-build-a-high-performance-component-733311ec91b6">Why I Stripped My UI Library to Build a High-Performance Component</a> was originally published in <a href="https://medium.com/pickme-engineering-blog">The PickMe Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prototype: Design Patterns with Java]]></title>
            <link>https://medium.com/@ashantiwankaperera/prototype-design-patterns-with-java-23180d486f9f?source=rss-215563e04d5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/23180d486f9f</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[oop]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[prototype-design-pattern]]></category>
            <category><![CDATA[creational-design-pattern]]></category>
            <dc:creator><![CDATA[Ashan Perera]]></dc:creator>
            <pubDate>Tue, 16 Dec 2025 05:16:42 GMT</pubDate>
            <atom:updated>2025-12-16T05:16:42.864Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zUcoUm6nwonUayyyy3YGSQ.png" /></figure><blockquote><strong>Prototype</strong> is a creational design pattern that lets you copy existing objects without making your code dependent on their classes.</blockquote><p>In programming, creating a copy or a clone of an object instance is a common thing used in almost every application.</p><p>The typical not-so-efficient way to do this is to copy every attribute from the first instance to the newly created second instance separately.</p><pre>Car car_1 = new Car();<br>    car_1.brand = &quot;Honda&quot;;<br>    car_1.model = &quot;Civic&quot;;<br>    car_1.color = &quot;Black&quot;;<br>    <br>Car car_2 = new Car();<br>    car_2.brand = car_1.brand;<br>    car_2.model = car_1.model;<br>    car_2.color = car_1.color;</pre><p>Normally, if we follow OOP concepts, a copy or a clone of an object can be created by utilizing a constructor in the class that takes an instance of the same object as the argument and creates a new object.</p><pre>public class Car {<br>    private String brand;<br>    private String model;<br>    private String color;<br>    <br>    public Car(String brand, String model, String color) {<br>        this.brand = brand;<br>        this.model = model;<br>        this.color = color;<br>    }<br>    <br>    public Car(Car car) {<br>        this.brand = car.brand;<br>        this.model = car.model;<br>        this.name = car.name;<br>    }<br>}</pre><p>Now this construct method can be used to create a copy.</p><pre>Car car_1 = new Car(&quot;Honda&quot;, &quot;Civic&quot;, &quot;Black&quot;);<br>Car car_2 = new Car(car_1);</pre><p>Still, this is so generic and not well optimized. There is a specific design pattern, well optimized and efficient, which is specially designed for cloning object instances called the Prototype design pattern.</p><h3>Code</h3><p>The simple idea of this pattern is to move the cloning or copying process from the object class to the actual object instance.</p><p>First, create an interface “<em>Prototype</em>” as the template for the classes that should have the capability to clone.</p><pre>public class Prototype {<br>        Car clone();<br>}</pre><p>Then, take the “<em>Car</em>” class we created earlier and implement the “<em>Prototype</em>” interface and necessary modifications.</p><pre>public class Car implements Prototype {<br>    private String brand;<br>    private String model;<br>    private String color;<br>    <br>    public Car(String brand, String model, String color) {<br>        this.brand = brand;<br>        this.model = model;<br>        this.color = color;<br>    }<br>    <br>    public Car(Car car) {<br>        this.brand = car.brand;<br>        this.model = car.model;<br>        this.name = car.name;<br>    }<br>    <br>    @Override<br>    public Car clone() {<br>        return new Car(this);<br>    }<br>}</pre><p>Now this “<em>clone</em>” method can be used to create copies or clones of the object.</p><pre>Car car_1 = new Car(&quot;Honda&quot;, &quot;Civic&quot;, &quot;Black&quot;);<br>Car car_2 = car_1.clone();</pre><p>That&#39;s it!</p><p>Because this design pattern is so simple to implement yet powerful, it is widely used in a vast range of real-world use cases.</p><h3>More</h3><p>Let&#39;s see a use case where multiple non-identical objects can be easily cloned using this design pattern.</p><p>First, let&#39;s create an abstract class called “<em>Vehicle</em>” and move the clone method to that class as an abstract method.</p><pre>public abstract class Vehicle {<br>    private String brand;<br>    private String model;<br>    private String color;<br>    <br>    protected Vehicle(Vehicle vehicle) {<br>        this.brand = vehicle.brand;<br>        this.model = vehicle.model;<br>        this.color = vehicle.color;<br>    }<br>    <br>    public abstract Vehicle clone();<br>}</pre><p>Now let&#39;s create two classes, “<em>Car</em>” and “<em>Bike</em>” extended from the Vehicle class with the clone method as explained before.</p><pre>public class Car extends Vehicle {<br>    private int no_doors;<br>    <br>    public Car() { }<br>    <br>    public Car(Car car) {<br>        super(car);<br>        this.no_doors = car.no_doors;<br>    }<br>    <br>    @Override<br>    public Car clone() {<br>        return new Car(this);<br>    }<br>}</pre><pre>public class Bike extends Vehicle {<br>    private boolean passenger;<br>    <br>    public Bike() { }<br>    <br>    public Bike(Bike bike) {<br>        super(bike);<br>        this.passenger = car.passenger;<br>    }<br>    <br>    @Override<br>    public Bike clone() {<br>        return new Bike(this);<br>    }<br>}</pre><p>Now imagine there is an array of Vehicles containing Cars and Bikes.</p><p>Although those elements aren&#39;t the same since both of these classes are extended from the “<em>Vehicle</em>” class, a copy of the array can be easily created as follows.</p><pre>public void clone(List&lt;Vehicle&gt; vehicles) {<br>        List&lt;Vehicle&gt; clonedVehicles = new ArrayList&lt;&gt;();<br>        for(Vehicle vehicle : vehicles) {<br>            clonedVehicles.add(vehicle.clone());<br>        }<br>    }</pre><p>Easy right?</p><p>This is only one simple use case of this design pattern. There are many more interesting use cases of this design pattern that I suggest you learn from your own.</p><p>More about Prototype and other design patterns can be found in the following link.</p><p><a href="https://refactoring.guru/design-patterns/prototype">Prototype</a></p><p>Thank You!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23180d486f9f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Web Workers: The Secret to a Smooth, Fast Frontend]]></title>
            <link>https://medium.com/@ashantiwankaperera/web-workers-the-secret-to-a-smooth-fast-frontend-a8c30405fb88?source=rss-215563e04d5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8c30405fb88</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[webworker]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[frontend-performance]]></category>
            <dc:creator><![CDATA[Ashan Perera]]></dc:creator>
            <pubDate>Sat, 25 Oct 2025 09:50:52 GMT</pubDate>
            <atom:updated>2025-10-25T10:29:58.091Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lvvcl2KZh0hB4uucw6_xiw.gif" /></figure><h3>Introduction</h3><p>Modern web apps do a lot — data crunching, animations, complex UIs — all on JavaScript’s single main thread. When that thread gets busy, your app lags, freezes, or drops frames.</p><p>That’s where <strong>Web Workers</strong> shine. They let you offload heavy tasks to background threads so the main thread stays smooth and responsive. In a world where milliseconds define user experience, moving computation off the UI thread is one of the simplest yet most effective ways to boost real-world performance.</p><p>In this tutorial, we will build a simple form, break it by giving it a CPU-heavy load, and fix it using <strong>Web Workers</strong>.</p><h3>Let&#39;s Start Coding</h3><p>First, let&#39;s spin a fresh ReactJS TypeScript project using Vite.</p><pre>npm create vite@latest react-app -- --template react-ts</pre><p>This will come with Vite&#39;s default boilerplate code, which we don&#39;t need, so clean it as well.</p><p>After that, we need to install the packages that we need for the application. For this example, I&#39;m going to use “<em>react-hook-form”</em> because it&#39;s the easiest to use as a standalone form. You can also use others, such as “<em>Ant Design Form”</em> or “<em>TanStack Form</em>”, to your liking.</p><pre>npm install react-hook-form</pre><p>Then we will create a simple form with very simple validation that will run tightly coupled with the DOM, which will run on the same main thread.</p><h4>Creating a simple form</h4><p>First, let&#39;s create the type of the form in “<em>src/from/type.ts”</em></p><pre>export type FormData = {<br>  userName: string;<br>  email: string;<br>  age: number;<br>};</pre><p>Then create our “<em>SimpleForm</em>” component in “<em>src/form/form.tsx”</em></p><pre>import type { FC } from &quot;react&quot;;<br>import { useForm } from &quot;react-hook-form&quot;;<br>import type { FormData } from &quot;./type&quot;;<br><br>import &quot;./form.css&quot;;<br><br>const SampleForm: FC = () =&gt; {<br>  const {<br>    register,<br>    handleSubmit,<br>    formState: { errors },<br>  } = useForm&lt;FormData&gt;({ mode: &quot;onBlur&quot; });<br><br>  const onSubmit = (data: FormData) =&gt; {<br>    console.log(&quot;Submitted:&quot;, data);<br>    alert(&quot;Simple form submitted! Check console.&quot;);<br>  };<br><br>  return (<br>    &lt;form onSubmit={handleSubmit(onSubmit)} style={{ maxWidth: 480 }}&gt;<br>      &lt;h2&gt;Simple Form&lt;/h2&gt;<br><br>      &lt;div className=&quot;form-group&quot;&gt;<br>        &lt;label&gt;Username&lt;/label&gt;<br>        &lt;input<br>          {...register(&quot;userName&quot;, {<br>            required: &quot;Username is required&quot;,<br>            minLength: { value: 3, message: &quot;Minimum 3 characters&quot; },<br>          })}<br>        /&gt;<br>        {errors.userName &amp;&amp; (<br>          &lt;span className=&quot;error&quot;&gt;{errors.userName.message}&lt;/span&gt;<br>        )}<br>      &lt;/div&gt;<br><br>      &lt;div className=&quot;form-group&quot;&gt;<br>        &lt;label&gt;Email&lt;/label&gt;<br>        &lt;input<br>          {...register(&quot;email&quot;, {<br>            required: &quot;Email required&quot;,<br>            pattern: { value: /^\S+@\S+$/i, message: &quot;Invalid email&quot; },<br>          })}<br>        /&gt;<br>        {errors.email &amp;&amp; &lt;span className=&quot;error&quot;&gt;{errors.email.message}&lt;/span&gt;}<br>      &lt;/div&gt;<br><br>      &lt;div className=&quot;form-group&quot;&gt;<br>        &lt;label&gt;Age&lt;/label&gt;<br>        &lt;input<br>          type=&quot;number&quot;<br>          {...register(&quot;age&quot;, {<br>            required: &quot;Age required&quot;,<br>            validate: (v) =&gt; (v &lt;= 0 ? &quot;Must be valid age&quot; : true),<br>          })}<br>        /&gt;<br>        {errors.age &amp;&amp; &lt;span className=&quot;error&quot;&gt;{errors.age.message}&lt;/span&gt;}<br>      &lt;/div&gt;<br><br>      &lt;button type=&quot;submit&quot;&gt;Submit&lt;/button&gt;<br>    &lt;/form&gt;<br>  );<br>};<br><br>export default SampleForm;</pre><p>And make it a bit nicer using the following CSS in “<em>src/form/form.css”</em></p><pre>form {<br>  border: 1px solid #ccc !important;<br>  border-radius: 12px;<br>  padding: 24px;<br>}<br><br>.form-group {<br>  margin-bottom: 1rem;<br>  text-align: left;<br><br>  .error {<br>    color: red;<br>    font-size: small;<br>    line-height: 0%;<br>  }<br>}</pre><p>Then you should be able to see the following simple form with validation running.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*yz_fNA-r9O14fBDbPiLB2w.png" /><figcaption>simple form with default form validation</figcaption></figure><p>At this stage, the form is running smoothly while running the validations instantaneously. This is more than enough for 90% of the UIs frontend devs come across. But once in a while, there is a UI with a form or similar component where we need to run heavy computation like validation on the client end, where it pushes the boundaries of JavaScript, like blocking the main thread, which will introduce noticeable UI issues.</p><p>In such occasions, we need to think a bit smarter and use other available resources to optimize our workflow so that the star of the show, our main thread, stays free, only responsible for rendering the UI.</p><h4>Adding heavy computation</h4><p>First, let&#39;s create our validation function in “<em>src/form/validation.ts”. </em>In this function, we will run the validations from all the fields in the form, and we will introduce an artificial CPU-heavy load calculation to really push our system to its limits.</p><pre>import type { FormData } from &quot;./type&quot;;<br><br>export const validation = (data: FormData): Record&lt;string, string&gt; =&gt; {<br>  const start = performance.now();<br>  while (performance.now() - start &lt; 1000) {<br>    Math.sqrt(Math.random() * 1e8);<br>  }<br><br>  const errors: Record&lt;string, string&gt; = {};<br><br>  if (!data.userName || data.userName.length &lt; 3)<br>    errors.userName = &quot;Username must be at least 3 characters&quot;;<br><br>  if (!/^\S+@\S+$/.test(data.email)) errors.email = &quot;Email format is invalid&quot;;<br><br>  if (data.age &lt;= 0) errors.age = &quot;Must be valid age&quot;;<br><br>  return errors;<br>};</pre><p>Now we will modify our form to run this function each time our form field values change.</p><pre>import { type FC, useEffect } from &quot;react&quot;;<br>import { useForm } from &quot;react-hook-form&quot;;<br>import type { FormData } from &quot;./type&quot;;<br><br>import &quot;./form.css&quot;;<br><br>import { validation } from &quot;./validation&quot;;<br><br>const SampleForm: FC = () =&gt; {<br>  const {<br>    register,<br>    watch,<br>    setError,<br>    clearErrors,<br>    formState: { errors },<br>  } = useForm&lt;FormData&gt;({ mode: &quot;onChange&quot; });<br><br>  const values = watch();<br><br>  useEffect(() =&gt; {<br>    const validationErrors = validation(values);<br><br>    clearErrors();<br><br>    Object.entries(validationErrors).forEach(([key, message]) =&gt; {<br>      setError(key as keyof FormData, { type: &quot;manual&quot;, message });<br>    });<br>  }, [values, clearErrors, setError]);<br><br>  return (<br>    &lt;form style={{ maxWidth: 480 }}&gt;<br>      &lt;h2&gt;Simple Form&lt;/h2&gt;<br><br>      &lt;div className=&quot;form-group&quot;&gt;<br>        &lt;label&gt;Username&lt;/label&gt;<br>        &lt;input {...register(&quot;userName&quot;)} /&gt;<br>        {errors.userName &amp;&amp; (<br>          &lt;span className=&quot;error&quot;&gt;{errors.userName.message}&lt;/span&gt;<br>        )}<br>      &lt;/div&gt;<br><br>      &lt;div className=&quot;form-group&quot;&gt;<br>        &lt;label&gt;Email&lt;/label&gt;<br>        &lt;input {...register(&quot;email&quot;)} /&gt;<br>        {errors.email &amp;&amp; &lt;span className=&quot;error&quot;&gt;{errors.email.message}&lt;/span&gt;}<br>      &lt;/div&gt;<br><br>      &lt;div className=&quot;form-group&quot;&gt;<br>        &lt;label&gt;Age&lt;/label&gt;<br>        &lt;input {...register(&quot;age&quot;)} /&gt;<br>        {errors.age &amp;&amp; &lt;span className=&quot;error&quot;&gt;{errors.age.message}&lt;/span&gt;}<br>      &lt;/div&gt;<br><br>      &lt;button type=&quot;submit&quot;&gt;Submit&lt;/button&gt;<br>    &lt;/form&gt;<br>  );<br>};<br><br>export default SampleForm;</pre><p>Now, if you check the form, it will start to lag drastically. There should be a visible delay between keypress and UI render. You can see the CPU usage in the performance tab in Dev Tools.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*n3V5SuShrAWVOUt9Dluu_Q.png" /></figure><p>Well, Congratulations🎉, everything is red, you&#39;ve done it. But don&#39;t worry, we got it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*VjuuXfrmstgyWzvtlyRfng.gif" /></figure><h4>Utilizing a web worker to optimize performance</h4><p>To tackle such scenarios browser has provided us an API called <strong>Web Worker</strong>. Its sole purpose is to run JavaScript code in a <strong>separate background thread</strong>, away from the main UI thread.</p><p>Although JavaScript is single-threaded, web workers allow us to smartly distribute heavy loads across threads, allowing parallelism. You can read more about the Web Worker API in the following document.</p><p><a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API">Web Workers API - Web APIs | MDN</a></p><p>When it comes to using web workers, there are a few ways. The most basic way is to use the worker API exposed to JavaScript by the browser.</p><p>Also, there are widely used packages like <strong>“Comlink”</strong> that abstract the implementation of the web worker without making it harder.</p><p><a href="https://github.com/GoogleChromeLabs/comlink#readme">GitHub - GoogleChromeLabs/comlink: Comlink makes WebWorkers enjoyable.</a></p><p>Since we are using ReactJS, and in React, hooks are a very common practice, we are going to use a package called <strong>“useWorker”</strong><em>.</em></p><p><a href="https://useworker.js.org/">useWorker | useWorker</a></p><h4>Implementing useWorker</h4><p>Firstly, we need to install the useWoker package.</p><pre>npm install @koale/useworker</pre><p>Then we need to slightly modify the “<em>formData”</em> type because we are going to pass that data into a separate thread without the UI, so sometimes undefined values can be passed as “<em>formData</em>”.</p><pre>export type FormData = {<br>  userName?: string;<br>  email?: string;<br>  age?: number;<br>};</pre><p>Then the validation function to support those changes.</p><pre>import type { FormData } from &quot;./type&quot;;<br><br>export const validation = (data: FormData): Record&lt;string, string&gt; =&gt; {<br>  const start = performance.now();<br>  while (performance.now() - start &lt; 1000) {<br>    Math.sqrt(Math.random() * 1e8);<br>  }<br><br>  const errors: Record&lt;string, string&gt; = {};<br><br>  if (!data.userName || data.userName.length &lt; 3)<br>    errors.userName = &quot;Username must be at least 3 characters&quot;;<br><br>  if (!data.email || !/^\S+@\S+$/.test(data.email))<br>    errors.email = &quot;Email format is invalid&quot;;<br><br>  const age = Number(data.age);<br>  if (isNaN(age) || age &lt;= 0) errors.age = &quot;Must be valid age&quot;;<br><br>  return errors;<br>};</pre><p>Next, we are going to modify our form component, where we will run the validation asynchronously in a separate thread using useWorker.</p><pre>import { type FC, useEffect, useState } from &quot;react&quot;;<br>import { useForm, useWatch } from &quot;react-hook-form&quot;;<br>import { useWorker } from &quot;@koale/useworker&quot;;<br>import type { FormData } from &quot;./type&quot;;<br><br>import &quot;./form.css&quot;;<br><br>import { validation } from &quot;./validation&quot;;<br><br>const SampleForm: FC = () =&gt; {<br>  const {<br>    register,<br>    setError,<br>    clearErrors,<br>    formState: { errors },<br>    control,<br>  } = useForm&lt;FormData&gt;({ mode: &quot;onChange&quot; });<br><br>  const [validateWorker, { kill }] = useWorker(validation);<br>  const [isValidating, setIsValidating] = useState(false);<br>  const values = useWatch&lt;FormData&gt;({ control });<br><br>  useEffect(() =&gt; {<br>    if (!values) return;<br><br>    let isCancelled = false;<br><br>    const runValidation = async () =&gt; {<br>      if (!values) return;<br>      if (<br>        values.userName === undefined &amp;&amp;<br>        values.email === undefined &amp;&amp;<br>        values.age === undefined<br>      )<br>        return;<br><br>      setIsValidating(true);<br>      try {<br>        const result = await validateWorker(values);<br><br>        if (isCancelled) return;<br><br>        clearErrors();<br><br>        Object.entries(result).forEach(([key, message]) =&gt; {<br>          setError(key as keyof FormData, { type: &quot;manual&quot;, message });<br>        });<br>      } catch (err) {<br>        console.error(&quot;Worker validation failed:&quot;, err);<br>      } finally {<br>        if (!isCancelled) setIsValidating(false);<br>      }<br>    };<br><br>    const timeout = setTimeout(runValidation, 300);<br><br>    return () =&gt; {<br>      isCancelled = true;<br>      clearTimeout(timeout);<br>    };<br>  }, [values, clearErrors, setError, validateWorker]);<br><br>  useEffect(() =&gt; {<br>    return () =&gt; {<br>      kill();<br>    };<br>  }, [kill]);<br><br>  return (<br>    &lt;form style={{ maxWidth: 480 }}&gt;<br>      &lt;h2&gt;Simple Form&lt;/h2&gt;<br><br>      &lt;div className=&quot;form-group&quot;&gt;<br>        &lt;label&gt;Username&lt;/label&gt;<br>        &lt;input {...register(&quot;userName&quot;)} /&gt;<br>        {errors.userName &amp;&amp; (<br>          &lt;span className=&quot;error&quot;&gt;{errors.userName.message}&lt;/span&gt;<br>        )}<br>      &lt;/div&gt;<br><br>      &lt;div className=&quot;form-group&quot;&gt;<br>        &lt;label&gt;Email&lt;/label&gt;<br>        &lt;input {...register(&quot;email&quot;)} /&gt;<br>        {errors.email &amp;&amp; &lt;span className=&quot;error&quot;&gt;{errors.email.message}&lt;/span&gt;}<br>      &lt;/div&gt;<br><br>      &lt;div className=&quot;form-group&quot;&gt;<br>        &lt;label&gt;Age&lt;/label&gt;<br>        &lt;input {...register(&quot;age&quot;)} type=&quot;number&quot;/&gt;<br>        {errors.age &amp;&amp; &lt;span className=&quot;error&quot;&gt;{errors.age.message}&lt;/span&gt;}<br>      &lt;/div&gt;<br><br>      &lt;button type=&quot;submit&quot;&gt;<br>        Submit<br>      &lt;/button&gt;<br>    &lt;/form&gt;<br>  );<br>};<br><br>export default SampleForm;</pre><p>Now, if you run the UI, you should see that it&#39;s buttery smooth again, and let&#39;s take a look at the Dev Tools as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*zwa_xK8PjC-rTtpKKKMpzw.png" /></figure><p>Well, as expected, it&#39;s green. But you might notice that the error messages from the validation take some time to appear after key strokes. That&#39;s because we are now running the validation asynchronously, so it takes some time to validate after the input.</p><p>So it&#39;s our duty as <strong>responsible developers</strong>😉 to let the user know that there is a validation running in the background and block the form action (submit) until the validation is completed and everything is good to go.</p><p>To do that, first let&#39;s check if there are errors in the validation of the form.</p><pre><br>  const isErrors = Object.keys(errors).length &gt; 0;</pre><p>Next, add a small spinner to the submit button and disable it while the validation is running and if there is an error.</p><pre>&lt;button type=&quot;submit&quot; disabled={isValidating || isErrors}&gt;<br>  {isValidating &amp;&amp; &lt;div className=&quot;loader&quot; /&gt;}<br>  &lt;span&gt;Submit&lt;/span&gt;<br>&lt;/button&gt;</pre><p>Finally, some CSS magic to make everything a bit nicer.</p><pre>button {<br>  display: inline-flex;<br>  align-items: center;<br>  gap: 0.5em;<br>}<br><br>.loader {<br>  border: 2px solid #d3d3d3;<br>  border-top: 2px solid #116eab;<br>  border-radius: 50%;<br>  width: 14px;<br>  height: 14px;<br>  animation: spin 2s linear infinite;<br>}<br><br>@keyframes spin {<br>  0% {<br>    transform: rotate(0deg);<br>  }<br>  100% {<br>    transform: rotate(360deg);<br>  }<br>}</pre><p>And that&#39;s it. You&#39;ve successfully implemented a web worker to offload CPU-intensive workload from the main thread to prevent UI blocking.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*JQVpVL5XveRit92iuRuO9Q.gif" /></figure><p>You can find a hosted version of this example in the link below with an FPS monitor to see the difference before and after implementing the web worker.</p><p><a href="https://web-worker-ex.netlify.app/">https://web-worker-ex.netlify.app/</a></p><p>This is not the end of web workers. They can be used to implement complex workflows efficiently, even more than one worker at a time. So do your own research and find more useful ways to utilize this valuable API.</p><p>The following repo contains all the code related to this example.</p><p><a href="https://github.com/AshanPerera98/use-worker-ex">GitHub - AshanPerera98/use-worker-ex: Example on using useWorker to improve performance of a use-hook-form in react</a></p><p>Feel free to comment on the new developments in web optimization or your experience and findings on the topic.</p><p><strong>Happy Coding!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8c30405fb88" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Builder: Design Patterns with Java]]></title>
            <link>https://medium.com/@ashantiwankaperera/builder-design-patterns-with-java-17ed0490a6f2?source=rss-215563e04d5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/17ed0490a6f2</guid>
            <category><![CDATA[creational-design-pattern]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[builder-pattern]]></category>
            <category><![CDATA[oop]]></category>
            <dc:creator><![CDATA[Ashan Perera]]></dc:creator>
            <pubDate>Thu, 13 Mar 2025 12:57:24 GMT</pubDate>
            <atom:updated>2025-03-13T12:57:24.292Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2CYpF9o946hepnCXfJEpgw.png" /></figure><blockquote><strong>Builder</strong> is a creational design pattern that lets you construct complex objects step by step. The pattern allows you to produce different types and representations of an object using the same construction code.</blockquote><p>This design pattern is designed to tackle the trouble of making large objects with many attributes. Sometimes in real-world applications, developers have to create object classes that have a large amount of attributes that are really hard to construct using traditional methods aren&#39;t efficient.</p><p>Most of the time, each object created by the class may have different attributes, and all the attributes are not required every time. So using traditional constructors leads to creating multiple constructors to handle each different attribute set.</p><p>This method&#39;s core concept is to decouple the creation of the object (“<em>constructor</em>”) from the object (“<em>class</em>”) itself. We can call it the “<em>builder</em>”.</p><p>Take the class “<em>Car</em>” as an example with attributes “<em>brand</em>”, “<em>name</em>”, “<em>color</em>”, “<em>number of doors</em>”, “<em>number of seats</em>” and the “<em>engine</em>”.</p><p>Now let&#39;s create a car with the traditional constructor.</p><pre>Car car = new Car(&quot;Honda&quot;, &quot;Civic&quot;, &quot;red&quot;, 4, 5, &quot;v6&quot;);</pre><p>Let&#39;s create another car with no color.</p><pre>Car car = new Car(&quot;Honda&quot;, &quot;Civic&quot;, null, 4, 5, &quot;v6&quot;);</pre><p>Here you can see every time we create an object from the class, we don&#39;t need all the attributes. Rather than parsing “<em>null,</em>” a better option is to create a new constructor.</p><pre>Car car = new Car(&quot;Honda&quot;, &quot;Civic&quot;, 4, 5, &quot;v6&quot;);<br>Car car = new Car(&quot;Honda&quot;, &quot;Civic&quot;, 4, 5);<br>Car car = new Car(&quot;Honda&quot;, &quot;Civic&quot;);</pre><p>Now you can see that the constructors are overloading. The more attributes we have for the class, the more constructors we need. That is not good.</p><p>Now let&#39;s try to decouple the creational code (“<em>construct</em>”) from the class itself and move it to a separate object (“<em>builder</em>”) as the pattern suggests.</p><h3>Code</h3><p>First, create a class for the object that we are going to create from the builder. In this case, it is the “<em>Car</em>” class.</p><pre>public class Car {<br>    private String brand;<br>    private String name;<br>    private String color;<br>    private int no_doors;<br>    private int no_seats;<br>    private String engine;<br>    <br>    Car(String brand, String name, String color, int no_doors, int no_seats, String engine) {<br>        this.brand = brand;<br>        this.name = name;<br>        this.color = color;<br>        this.no_doors = no_doors;<br>        this.no_seats = no_seats;<br>        this.engine = engine;<br>    }<br>}</pre><p>As you can see, the object class contains all the attributes and one large default constructor. This way, the builder should always make the object rather than calling the direct constructor from the object class.</p><h4>Builder</h4><p>Let&#39;s create the builder called “<em>CarBuilder</em>” for the car.</p><pre>public class CarBuilder{<br>    private String brand;<br>    private String name;<br>    private String color;<br>    private int no_doors;<br>    private int no_seats;<br>    private String engine;<br>    <br>    public CarBuilder brand(String brand) {<br>        this.brand = brand;<br>    }<br>    <br>    public CarBuilder name(String name) {<br>        this.name = name;<br>    }<br>    <br>    public CarBuilder color(String color) {<br>        this.color = color;<br>    }<br>    <br>    public CarBuilder no_doors(int no_doors) {<br>        this.no_doors = no_doors;<br>    }<br>    <br>    public CarBuilder no_seats(int no_seats) {<br>        this.no_seats = no_seats;<br>    }<br>    <br>    public CarBuilder engine(String engine) {<br>        this.engine = engine;<br>    }<br>    <br>    public Car build() {<br>        return new Car(brand, name, color, no_doors, no_seats, engine);<br>    }<br>}</pre><p>As you can see, the builder class contains a set of setters-like methods to set each attribute and a build method that invokes the constructor from the object class and returns the newly created object.</p><p>Next to build a new car instance, we need to follow the following process.</p><pre>CarBuilder car_builder = new CarBuilder();<br>        <br>car_builder.brand(&quot;Honda&quot;);<br>car_builder.name(&quot;Civic&quot;);<br>car_builder.color(&quot;red&quot;);<br>car_builder.no_doors(4);<br>car_builder.no_seats(5);<br>car_builder.engine(&quot;v6&quot;);<br>        <br>Car car = car_builder.build();</pre><p>Here you can see that based on the preferences only the wanted attributes can be set to the object and finally using the build method the object instance can be created.</p><p>Now let&#39;s imagine a situation where we want to create Honda Civics but the color may change on each instance. In this scenario, every instance has a set of common attributes like “<em>brand</em>” and “<em>name</em>”.</p><p>So we can optimize this pattern to facilitate these requirements.</p><h4>Director</h4><p>Although the above-mentioned requirement can be achieved by the current implementation, it&#39;s not efficient because we have to set the same “<em>name</em>” and the “<em>brand</em>” for all the instances again and again.</p><p>To overcome this problem, we create a “<em>director</em>”.</p><pre>public class Director{<br>    <br>    public void buildCivic(CarBuilder builder) {<br>        builder.brand(&quot;Honda&quot;);<br>        builder.name(&quot;Civic&quot;);<br>        builder.no_doors(4);<br>        builder.no_seats(5);<br>        builder.engine(&quot;v6&quot;);<br>    }<br>    <br>    public void buildSupra(CarBuilder builder) {<br>        builder.brand(&quot;Toyota&quot;);<br>        builder.name(&quot;Supra&quot;);<br>        builder.no_doors(2);<br>        builder.no_seats(2);<br>        builder.engine(&quot;v8&quot;);<br>    }<br>}</pre><p>Here you can see the “<em>director</em>” class contains different methods that take a “<em>builder</em>” as an argument and populate each “<em>builder</em>” with a predefined set of attributes. So the sole purpose of the “<em>director</em>” is to partially construct an instance of an object using the “<em>builder</em>”.</p><p>Let’s try to create a red Supra and a blue Supra using “<em>director</em>”.</p><pre>Director director = new Director();<br>        <br>CarBuilder redSupraBuilder = new CarBuilder();<br>director.buildSupra(redSupraBuilder);<br>redSupraBuilder.color(&quot;red&quot;);<br>        <br>Car redSupra = redSupraBuilder.build();<br>        <br>CarBuilder blueSupraBuilder = new CarBuilder();<br>director.buildSupra(blueSupraBuilder);<br>blueSupraBuilder.color(&quot;blue&quot;);<br>        <br>Car blueSupra = blueSupraBuilder.build();</pre><p>Easy Right?</p><p>As you can see, we have removed lots of repetitive code from the creation of the object instance.</p><p>This is the basic concept and the implementation of the Builder design pattern. This can be further optimized and scaled up by using interfaces for both “<em>builder</em>” and “<em>director</em>” and implementing those in the real “<em>builder</em>” and “<em>director</em>” classes.</p><p>More about Builder and other design patterns can be found in the following link.</p><p><a href="https://refactoring.guru/design-patterns/builder">Builder</a></p><p>Thank You!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17ed0490a6f2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[End of Memoization with React 19? (React.memo, useCallback, useMemo)]]></title>
            <link>https://medium.com/@ashantiwankaperera/end-of-memorization-with-react-19-react-memo-usecallback-usememo-b8df7f18aba1?source=rss-215563e04d5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8df7f18aba1</guid>
            <category><![CDATA[memorization]]></category>
            <category><![CDATA[usecallback]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[usememo]]></category>
            <category><![CDATA[react-memo]]></category>
            <dc:creator><![CDATA[Ashan Perera]]></dc:creator>
            <pubDate>Tue, 10 Dec 2024 15:21:09 GMT</pubDate>
            <atom:updated>2025-06-08T04:23:24.292Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5QIQnQ9V8C98K3A-c3KRrQ.gif" /></figure><h3>Why Memoization?</h3><p>Normally React components get re-rendered based on three major factors.</p><ol><li>Change of props</li><li>Change of state</li><li>Re-rendering the parent component</li></ol><p>Imagine a situation where multiple levels of child components are nested in a parent component. Most of the time, the parent doesn&#39;t send all the props to its child; only the values that the child needs for rendering are passed down as props or using state.</p><p>But because of the third condition if a value only consumed by the parent is changed, then the parent gets re-rendered according to the new value and it will cause all the child components to re-render although they do not have any change. This becomes a huge overhead when the component structure is deeply nested and complicated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*cNPmvKx_TNIKNcHBtg_MkQ.png" /><figcaption>Unpotimized rendering chain</figcaption></figure><p>In the above example, red color means changing and rendering and green means not changing. Only the “<em>Prop_3” </em>prop is changing, which should trigger the rendering of the parent component. However, it also renders all the child components, resulting in 6 more unnecessary renders, although nothing changes in those child components.</p><p>To overcome this issue React has three memoization mechanisms built in to optimize the rendering of the components.</p><ol><li>React.memo</li><li>useCallback</li><li>useMemo</li></ol><p>By utilizing those we can reduce the overhead of unnecessary re-renders in the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*cgFDTHPG-vEw5pbWhlKXOg.png" /><figcaption>Optimized component rendering</figcaption></figure><p>An optimized component tree will only re-render the necessary components when a prop or a state change happens. In the optimized example when “<em>Prop_3</em>” is changing only the parent gets rendered because it&#39;s the only component that consumes the “<em>Prop_3</em>” value and child components stay the same although the parent is re-rendered.</p><p>Now let&#39;s look at when, where, and how to use those memoization mechanisms.</p><h3>React.memo</h3><blockquote>memo lets you skip re-rendering a component when its props are unchanged.</blockquote><p>“<em>React.memo</em>” is a built-in function that will take a component as an argument memorize its props and return the new memorized component. so that the component will re-render only if the incoming props are changed.</p><pre>import React, { memo } from &quot;react&quot;;<br><br>const component = memo((props) =&gt; {<br>  return (<br>    &lt;&gt;<br>      &lt;div&gt;component&lt;/div&gt;<br>      &lt;div&gt;{props.content}&lt;/div&gt;<br>    &lt;/&gt;<br>  );<br>});<br><br>export default component;</pre><p><strong>“React.memo” is used to memorize incoming props.</strong></p><p><a href="https://react.dev/reference/react/memo">Read more about “React.memo” here…</a></p><h3>useCallback</h3><blockquote>useCallback is a React Hook that lets you cache a function definition between re-renders.</blockquote><p>This is a bit more complicated than “<em>React.memo</em>”. Let&#39;s look into the following example.</p><p>Here is a child component wrapped with “<em>React.memo</em>”.</p><pre>import React, { memo } from &quot;react&quot;;<br><br>const Child = memo((props) =&gt; {<br>  return (<br>    &lt;&gt;<br>      {console.log(&quot;child rendered&quot;)}<br>      &lt;h1&gt;Child&lt;/h1&gt;<br>      &lt;h3&gt;child value: {props.getData()}&lt;/h3&gt;<br>    &lt;/&gt;<br>  );<br>});<br><br>export default Child;</pre><p>This is the parent component that consumes it.</p><pre>import React, { useState } from &quot;react&quot;;<br>import Child from &quot;./child&quot;;<br><br>const Parent = () =&gt; {<br>  const [value, setValue] = useState(1);<br>  const [localValue, setLocalValue] = useState(1);<br><br>  const getData = () =&gt; {<br>    return value;<br>  };<br><br>  return (<br>    &lt;&gt;<br>      {console.log(&quot;parent rendered&quot;)}<br>      &lt;h1&gt;Parent&lt;/h1&gt;<br>      &lt;h3&gt;value : {value}&lt;/h3&gt;<br>      &lt;h3&gt;local value : {localValue}&lt;/h3&gt;<br><br>      &lt;button<br>        onClick={() =&gt; {<br>          setValue(value + 1);<br>        }}<br>      &gt;<br>        Click to change value<br>      &lt;/button&gt;<br><br>      &lt;button<br>        onClick={() =&gt; {<br>          setLocalValue(localValue + 1);<br>        }}<br>      &gt;<br>        Click to change local value<br>      &lt;/button&gt;<br><br>      &lt;Child getData={getData} /&gt;<br>    &lt;/&gt;<br>  );<br>};<br><br>export default Parent;</pre><p>Here the only prop passed to the child component is the “<em>getData</em>”<em> </em>function that will return the “<em>value</em>”.</p><p>Now if you test this although the child component is using “<em>React.memo</em>” it&#39;s clear that both the parent and the child will be re-rendered every time either the “<em>value </em>”or the “<em>localValue </em>”is changed.</p><p>This is happening due to how react initialize functions. The “<em>getData</em>” function is initialized inside the parent component and it&#39;s not memorized so that every time the parent component re-renders React will initialize the “<em>getData</em>” function which will be sent down to the child as a new function every time.</p><p>But we only need to change the “<em>getData</em>” function when the “<em>value</em>” state changes. This function can be memorized using “<em>useCallback</em>” as follows.</p><pre>  const getData = useCallback(() =&gt; {<br>    return value;<br>  }, [value]);</pre><p>This change will make the “<em>getData</em>” a memorized function and it&#39;s reinitialized only when the “<em>value</em>” state is changed as stated in the code by passing it into the dependency array.</p><p>Now if this is tested it&#39;s clear that the child will be re-rendered only and only when the “<em>value</em>” state changes.</p><p><strong>“useCallback” is used to memorize functions.</strong></p><p><a href="https://react.dev/reference/react/useCallback">Read more about “useCallback” here…</a></p><h3>useMemo</h3><blockquote>useMemo is a React Hook that lets you cache the result of a calculation between re-renders.</blockquote><p>Let&#39;s look at the following example of how to use “<em>useMemo</em>” for memoization.</p><pre>import React, { useState } from &quot;react&quot;;<br><br>const Component = () =&gt; {<br>  const [value, setValue] = useState(1);<br>  const [arr, setArr] = useState([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);<br><br>  const getMax = () =&gt; {<br>    console.log(&quot;large calculation&quot;);<br>    return Math.max(...arr);<br>  };<br><br>  const changeValue = () =&gt; {<br>    setValue(value + 1);<br>  };<br><br>  const changeArr = () =&gt; {<br>    const newArr = [...arr, arr[arr.length - 1] + 1];<br>    setArr(newArr);<br>  };<br>  return (<br>    &lt;&gt;<br>      &lt;h3&gt;value: {value}&lt;/h3&gt;<br>      &lt;h3&gt;array: {JSON.stringify(arr)}&lt;/h3&gt;<br>      &lt;h3&gt;max: {getMax()}&lt;/h3&gt;<br>      &lt;button onClick={changeValue}&gt;Change value&lt;/button&gt;<br>      &lt;button onClick={changeArr}&gt;Change array&lt;/button&gt;<br>    &lt;/&gt;<br>  );<br>};<br><br>export default Component;</pre><p>In this component imagine “<em>getMax</em>” is a function that depends on a state that will take lots of processing power or a time-consuming operation. Its value will only change when the “<em>arr</em>” state is changed. But in this example even when the “<em>value</em>” state changes “<em>getMax</em>” function will run and return the same value as the previous.</p><p>This is a waste of resources and poorly optimized. “<em>useMemo</em>” hook can be utilized here to only execute this heavy “<em>getMax</em>” calculation when the dependent “<em>value</em>” state is changed.</p><pre>import React, { useMemo, useState } from &quot;react&quot;;<br><br>const Component = () =&gt; {<br>  const [value, setValue] = useState(1);<br>  const [arr, setArr] = useState([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);<br><br>  const getMax = () =&gt; {<br>    console.log(&quot;large calculation&quot;);<br>    return Math.max(...arr);<br>  };<br><br>  const memorizedMax = useMemo(() =&gt; getMax(), [arr]);<br><br>  const changeValue = () =&gt; {<br>    setValue(value + 1);<br>  };<br><br>  const changeArr = () =&gt; {<br>    const newArr = [...arr, arr[arr.length - 1] + 1];<br>    setArr(newArr);<br>  };<br>  return (<br>    &lt;&gt;<br>      &lt;h3&gt;value: {value}&lt;/h3&gt;<br>      &lt;h3&gt;array: {JSON.stringify(arr)}&lt;/h3&gt;<br>      &lt;h3&gt;max: {memorizedMax}&lt;/h3&gt;<br>      &lt;button onClick={changeValue}&gt;Change value&lt;/button&gt;<br>      &lt;button onClick={changeArr}&gt;Change array&lt;/button&gt;<br>    &lt;/&gt;<br>  );<br>};<br><br>export default Component;</pre><p>Now this resource-heavy operation (“<em>getMax</em>”) executes only when the dependency array (“<em>arr</em>”) is changed.</p><p><strong>“<em>useMemo</em>” is used to memorize the results from functions.</strong></p><p><a href="https://react.dev/reference/react/useMemo">Read more about “useMemo” here…</a></p><h3>Don’t Memorize Everything!</h3><p>It seems like memorizing every possible scenario in the application will make it better optimized and faster right?</p><p><strong>Wrong!</strong> Sometimes actually memorizing is more costly than re-rendering the component.</p><p>Especially if there are small components like buttons, icons, titles, or very lightweight components that don&#39;t have any large calculations as internal logic or API calls involved it&#39;s better to let those components re-render than memorizing them.</p><h3>End of Memoization with React 19?</h3><p>For the longest time react did not have a compiler. With later versions of React 18, there was a beta version of a compiler and it seemed promising. With the release of React 19, the compiler is a live feature that will automatically add a compiling phase while building the React application.</p><p><a href="https://react.dev/blog/2024/02/15/react-labs-what-we-have-been-working-on-february-2024">Read more about the React compiler here…</a></p><p>One of the major functionalities of this compiler is to analyze the code and add memoization (“<em>memo</em>”, “<em>useCallback</em>”, “<em>useMemo</em>”) under the hood where it is needed.</p><p>This made developers think that React is going to deprecate memoization, which is not going to happen anytime soon. As for now React 19 compiler is adding memoization where it thinks should memoize but sometimes it misses a place or two.</p><p>The best thing to do right now is,</p><ol><li>if the React version is 18 or below add the memoizations manually where heavy calculations or heavy resources are rendered.</li><li>if the React version is 19 let the compiler do its thing and keep an eye on the dev tools and when you see an opportunity where code can be further optimized by manually memorizing, take matters into your own hands and do the modification.</li></ol><p>Feel free to comment on the new developments in memoization or your experience and findings on the topic.</p><p><strong>Happy coding!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8df7f18aba1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Abstract Factory: Design Patterns with Java]]></title>
            <link>https://medium.com/@ashantiwankaperera/abstract-factory-design-patterns-with-java-913176f95d27?source=rss-215563e04d5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/913176f95d27</guid>
            <category><![CDATA[creational-design-pattern]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[abstract-factory-pattern]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[oop]]></category>
            <dc:creator><![CDATA[Ashan Perera]]></dc:creator>
            <pubDate>Sat, 05 Oct 2024 14:35:09 GMT</pubDate>
            <atom:updated>2024-10-05T14:35:09.346Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cwoEDIlLC_Apv9YHdVcVOw.png" /></figure><blockquote><strong>Abstract Factory</strong> is a creational design pattern that lets you produce families of related objects without specifying their concrete classes.</blockquote><p>This pattern can be called an extension of the Factory Method design pattern. Since this pattern is based on the core concepts of the Factory Method pattern, I suggest first going through the Factory Method design pattern and getting a full understanding of how it works.</p><p>Below is a detailed article on the Factory Method pattern and its implementation.</p><p><a href="https://medium.com/@ashantiwankaperera/factory-method-design-patterns-with-java-6d80665bcdfa">Factory Method: Design Patterns with Java</a></p><p>Abstract Factory is like using multiple Factory Method patterns to handle the creation of multiple distinct products.</p><p>As the example let&#39;s take the same UI element button from the Factory Method example and add a new UI element checkbox.</p><h3>Code</h3><p>Let’s code this using Java.</p><p>First, create the first interface (“<em>product</em>”) button.</p><pre>public interface Button {<br>    void render();<br>}</pre><p>Then create two variations (“<em>concrete products</em>”) of the button.</p><pre>public class DesktopButton implements Button {<br><br>    public void render() {<br>        System.out.println(&quot;&lt;button&gt;Desktop Button&lt;/button&gt;&quot;);<br>    }<br>}</pre><pre>public class MobileButton implements Button {<br><br>    public void render() {<br>        System.out.println(&quot;&lt;button&gt;Mobile Button&lt;/button&gt;&quot;);<br>    }<br>}</pre><p>After that create the second interface (“<em>product</em>”) checkbox.</p><pre>public interface Checkbox {<br>    void render();<br>}</pre><p>And its two variations (“<em>concrete products</em>”) of the checkbox.</p><pre>public class DesktopCheckbox implements Checkbox {<br><br>    public void render() {<br>        System.out.println(&quot;&lt;input type=&quot;checkbox&quot;&gt;Desktop Checkbox&lt;/input&gt;&quot;);<br>    }<br>}</pre><pre>public class MobileCheckbox implements Checkbox {<br><br>    public void render() {<br>        System.out.println(&quot;&lt;input type=&quot;checkbox&quot;&gt;Mobile Checkbox&lt;/input&gt;&quot;);<br>    }<br>}</pre><p>Then create an interface (“<em>abstract factory</em>”) as the template for “<em>concrete factories</em>”.</p><pre>public interface UIkit {<br>    Button createButton();<br>    Checkbox createCheckbox();<br>}</pre><p>Now let&#39;s create the two “<em>concrete factories</em>” implementing the UIkit interface.</p><pre>public class DesktopUIkit implements UIkit {<br><br>    @Override<br>    public Button createButton() {<br>        return new DesktopButton();<br>    }<br><br>    @Override<br>    public Checkbox createCheckbox() {<br>        return new DesktopCheckbox();<br>    }<br>}</pre><pre>public class MobileUIkit implements UIkit {<br><br>    @Override<br>    public Button createButton() {<br>        return new MobileButton();<br>    }<br><br>    @Override<br>    public Checkbox createCheckbox() {<br>        return new MobileCheckbox();<br>    }<br>}</pre><p>This is the basic implementation of the Abstract Factory design pattern.</p><p>Now let’s see a simple implementation of this.</p><h3>Demo</h3><pre>public class Demo {<br>    private static UIKit uikit;<br><br>    public static void main(String[] args) {<br>        configure();<br><br>        Button button = UIkit.createButton();<br>        Checkbox checkbox = UIkit.createCheckbox();<br><br>        button.render();<br>        checkbox.render();<br>    }<br><br>    static void configure() {<br>        if (isMobile()) {<br>            uikit = new MobileUIkit();<br>        } else {<br>            uikit = new DesktopUIkit();<br>        }<br>    }<br><br>    static boolean isMobile() {<br>       /**<br>       * this method returns true if the device is a mobile device<br>       */<br>    }<br>}</pre><p>Thats it!</p><p>As you can see this is highly scalable and can add more “<em>products</em>” and “<em>concrete products</em>” if needed without affecting the current implementation. Also, this pattern follows both the “<em>open closed principle</em>” and the “<em>single responsibility principle</em>”.</p><p>More about Abstract Factory and other design patterns can be found in the following link.</p><p><a href="https://refactoring.guru/design-patterns/abstract-factory">Abstract Factory</a></p><p>Thank You!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=913176f95d27" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Micro Frontends: Small Pieces, Big Impact]]></title>
            <link>https://medium.com/@ashantiwankaperera/micro-frontends-small-pieces-big-impact-eb67d79e095d?source=rss-215563e04d5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb67d79e095d</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[micro-frontends]]></category>
            <category><![CDATA[module-federation]]></category>
            <category><![CDATA[single-spa]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Ashan Perera]]></dc:creator>
            <pubDate>Mon, 09 Sep 2024 15:52:25 GMT</pubDate>
            <atom:updated>2024-09-09T15:52:25.666Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vmecffzFM_733DKFSlx9sw.gif" /></figure><p>Modern-day web applications are far ahead of traditional websites. They pack serious punch when it comes to functionality and performance where they can go head to head with standalone applications in some cases.</p><p>With the increasing complexity of the web application, both front-end and backend more decoupled solutions were better than monolithic solutions. At the beginning of this revolution, microservices came into the picture where backend services were divided as microservices. With the rapid advancements in frontend technologies such as JavaScript frameworks, the same concept comes into play as micro-frontends.</p><blockquote><strong>In the realm of web development, micro frontends offer a revolutionary approach to building large-scale applications.</strong> Inspired by the success of microservices architecture, micro frontends break down complex frontends into smaller, independently deployable units. This modular approach allows for greater flexibility, scalability, and maintainability. By empowering teams to work autonomously on specific features, micro frontends foster innovation and accelerate development cycles.</blockquote><h4>Monolithic vs Micro-frontend</h4><p><strong>Monolithic Applications</strong> are like a single, large brick building. Everything is interconnected and tightly coupled. While they can be simpler to manage initially, they can become difficult to scale and maintain as they grow. Changes to one part of the application can impact the entire system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*hHkTfjyW3LvPaAURARGHEQ.png" /><figcaption>Monolithic Architecture</figcaption></figure><p><strong>Micro Frontends</strong> are more like a collection of modular buildings. Each building (or “micro frontend”) can be developed, deployed, and scaled independently. This makes them more flexible and adaptable to change. However, coordinating between different microservices can add complexity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*LuZFWmIRgxUrxEE690yYUw.png" /><figcaption>Micro-frontend Architecture</figcaption></figure><p>In essence, monolithic applications are simpler to build and maintain initially, but micro frontends offer greater scalability, flexibility, and the ability to handle complex, large-scale projects.</p><h3>Approaches</h3><p>The most interesting thing about micro frontends is that there is no right way or wrong way to achieve this. There are many different approaches and technologies that can be used with their own pros and cons.</p><p>Basically in micro frontends, a host (parent) application and guest (child) applications agree to a contract where it defines a set of rules on how to load, unload, communicate, share, consume, and interact with each other to work as a single application.</p><p>Next, let&#39;s look at some of the popular approaches and relevant technologies used in micro frontends.</p><h4>1. Iframes</h4><p>This is one of the earliest implementations of a micro frontend and to today&#39;s standards one of the least efficient and functional approaches. It utilizes the <strong>iframe</strong> tag from HTML which is designed to embed other web pages inside DOM. In the approach, parameters need to be sent as <strong>query params</strong> to the child web, and callbacks are handled as <strong>event dispatches and event listeners</strong>. The browser&#39;s global object (window) can also be really helpful for intercommunication.</p><p>Although this allows the developer to achieve micro frontend implementation to a certain extent it introduces a set of vulnerabilities, issues, and huge limitations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*Q6IX07zkifOgRMVipfIK2A.png" /><figcaption>Micro-frontend using iframes</figcaption></figure><p>You can learn more about iframes and how to use events by referring to the following resources.</p><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe">: The Inline Frame element - HTML: HyperText Markup Language | MDN</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/Events/Creating_and_triggering_events">Creating and triggering events - Event reference | MDN</a></li></ul><h4>2. OpenComponents</h4><p><strong>Open Components</strong> are reusable UI components that can be shared across multiple applications or teams. They are designed to be independent, modular, and customizable, making them ideal for micro frontend architectures.</p><p>Using OpenComponents consists of 3 simple steps</p><ol><li><strong>Design and Develop:</strong> Develop the component using a suitable framework or library like React, Angular, or Vue. Ensure the component is well-structured, modular, and adheres to best practices.</li><li><strong>Package and Publish:</strong> Package the component into a distributable format like an npm package and publish to OpenComponents. Consider using a build tool like Webpack to optimize the component’s size and performance.</li><li><strong>Integration:</strong> Import and use the OpenComponent as needed. Ensure proper configuration and setup to integrate the component seamlessly into your application’s context.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*XHFg6L7OJ3iqN_6UdgYckQ.png" /><figcaption>OpenComponents architecture</figcaption></figure><p>The key benefits of OpenComponents are reusability, maintainability, scalability, and collaboration.</p><p>Refer to the following link to learn more about OpenComponents and its implementations.</p><p><a href="https://opencomponents.github.io/">OpenComponents</a></p><h4>3. Single-SPA</h4><p><strong>Single-SPA</strong> is a JavaScript framework that provides a lifecycle management system for micro frontends. It acts as a unifying framework, coordinating the loading, mounting, and unmounting of different micro frontends within a single-page application.</p><p>It&#39;s the same as using OpenCompoentns but the difference is that the developer has to self-host the required host application and micro applications and do the necessary configurations to be Single-SPA compliant. Then Single-SPA will take care of mounting, unmounting, and communication between components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*vG8KnfG-McW22Q7S1M8W0Q.png" /><figcaption>Single-SPA architecture</figcaption></figure><p>Key features in Single-SPA are lifecycle management, routing, isolation, and flexibility.</p><p>Refer to the Single-SPA documentation from the following link to learn more.</p><p><a href="https://single-spa.js.org/">single-spa | single-spa</a></p><h4>4. Module Federation</h4><p><strong>Module Federation</strong> is a powerful feature introduced in Webpack 5 that allows different JavaScript applications to share code at runtime. It enables micro frontends to dynamically load and consume shared modules from other micro frontends or a shared module container.</p><p>Compared to all the above options this is the most advanced and customizable approach but you need an understanding of how Webpack works and this needs more development and deployment costs to implement.</p><p>In this approach, micro applications are written normally and at the end using Webpack config a new entry-point to the application is exposed as remote which will be served separately in runtime.</p><p>Then in the shell applications Webpack config those exposed entry-points will be consumed as remotes and will be available in the runtime of the shell application.</p><blockquote>If a framework like React or Angular is in use then <strong>this approach will require ejecting</strong> the underlying Webpack config, build and run scripts which will be a one-way operation. To overcome this issue a package like <strong>Craco</strong> can be used to overwrite the Webpack config without ejecting.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*mbZhsY4_UQ-g-OpC6AdkQQ.png" /><figcaption>Module-federation architecture</figcaption></figure><p>Some of the key benefits of module federation are dynamic code sharing, runtime flexibility, code reusability, and independent development.</p><p>Also since this is a highly customizable approach developers need to keep an eye on some of the best practices like</p><ul><li><strong>Shared Modules:</strong> Carefully select shared modules to avoid unnecessary dependencies and potential conflicts.</li><li><strong>Remote Entries:</strong> Ensure remote entries are well-structured and provide clear interfaces for shared modules.</li><li><strong>Performance Optimization:</strong> Consider caching shared modules and using techniques like code splitting to improve performance.</li><li><strong>Error Handling:</strong> Implement robust error handling to gracefully handle failures in loading or consuming shared modules.</li></ul><p>The following links will direct to module federation documentation from both Webpack and how to use Craco for configuring Webpack without ejecting which will explain in detail about the implementation.</p><ul><li><a href="https://webpack.js.org/concepts/module-federation/">Module Federation | webpack</a></li><li><a href="https://craco.js.org/docs/configuration/getting-started/">Getting Started | CRACO</a></li></ul><p>Micro-fontends has come a long journey with the advancements of modern web development and day by day there are new techniques and methods emerging in the topic. As the web continues to evolve, micro frontends are likely to become even more prevalent. By understanding and adopting these technologies, developers can build more modular, resilient, and future-proof applications.</p><p>Thank You!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb67d79e095d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Factory Method: Design Patterns with Java]]></title>
            <link>https://medium.com/@ashantiwankaperera/factory-method-design-patterns-with-java-6d80665bcdfa?source=rss-215563e04d5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d80665bcdfa</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[creational-design-pattern]]></category>
            <category><![CDATA[factory-method]]></category>
            <category><![CDATA[oop]]></category>
            <dc:creator><![CDATA[Ashan Perera]]></dc:creator>
            <pubDate>Sun, 28 Jul 2024 14:27:49 GMT</pubDate>
            <atom:updated>2024-07-28T14:27:49.658Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cxgCso2t2fyt-RF0blEKsg.png" /></figure><blockquote><strong>Factory Method</strong> is a creational design pattern that provides an interface for creating objects in a superclass but allows subclasses to alter the type of objects that will be created.</blockquote><p>This design pattern can be used to build applications with capabilities to expand more implementations in the future. Especially to add more variations like UI elements, products, and categories.</p><p>For this example let&#39;s take a real-world implementation of a UI element button that changes based on the device.</p><h3>Code</h3><p>Let’s code this using Java.</p><p>First, create an interface (“<em>products</em>”) as a template for the variations.</p><pre>public interface Button {<br>    void render();<br>    void onClick();<br>}</pre><p>Then implement this interface to create variations (“<em>concrete products</em>”) as needed.</p><p>For this example let&#39;s create two buttons for desktops and mobile.</p><pre>public class DesktopButton implements Button {<br><br>    public void render() {<br>        System.out.println(&quot;&lt;button&gt;Desktop Button&lt;/button&gt;&quot;);<br>        onClick();<br>    }<br><br>    public void onClick() {<br>        System.out.println(&quot;Clicked! Desktop button&quot;);<br>    }<br>}</pre><pre>public class MobileButton implements Button {<br><br>    public void render() {<br>        System.out.println(&quot;&lt;button&gt;Mobile Button&lt;/button&gt;&quot;);<br>        onClick();<br>    }<br><br>    public void onClick() {<br>        System.out.println(&quot;Clicked! Mobile button&quot;);<br>    }<br>}</pre><p>Now let&#39;s create an abstract class called UIkit. In the design pattern, this is called the “<em>creator</em>”.</p><pre>public abstract class UIkit {<br><br>    public void renderUI() {<br>        Button PrimaryButton = createButton();<br>        PrimaryButton.render();<br>    }<br><br>    public abstract Button createButton();<br>}</pre><p>Then create two UIkits for each device extending the “<em>creator</em>”. Those are called “<em>concrete creators</em>”.</p><pre>public class DesktopUIkit extends UIkit {<br><br>    @Override<br>    public Button createButton() {<br>        return new DesktopButton();<br>    }<br>}</pre><pre>public class MobileUIkit extends UIkit {<br><br>    @Override<br>    public Button createButton() {<br>        return new MobileButton();<br>    }<br>}</pre><p>This is the basic implementation of the Factory Method design pattern.</p><p>As you can see based on the need more “<em>concrete products</em>” and “<em>concrete creators</em>” can be added to the application without impacting the existing variations.</p><p>Now let&#39;s see a simple implementation of this.</p><h3>Demo</h3><pre>public class Demo {<br>    private static UIKit uikit;<br><br>    public static void main(String[] args) {<br>        configure();<br>        logic();<br>    }<br><br>    static void configure() {<br>        if (isMobile()) {<br>            uikit = new MobileUIkit();<br>        } else {<br>            uikit = new DesktopUIkit();<br>        }<br>    }<br><br>    static boolean isMobile() {<br>       /**<br>       * this method returns true if the device is a mobile device<br>       */<br>    }<br><br>    static void logic() {<br>        uikit.renderUI();<br>    }<br>}</pre><p>Thats it!</p><p>This pattern is heavily used to achieve scalability in the application. Also since this pattern heavily relies on inheritance and a single responsibility model this can be implemented easily with most languages.</p><p>More about Factory Method and other design patterns can be found in the following link.</p><p><a href="https://refactoring.guru/design-patterns/factory-method">Factory Method</a></p><p>Thank You!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d80665bcdfa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering State Management with Redux Toolkit: A Beginner’s Guide]]></title>
            <link>https://medium.com/@ashantiwankaperera/mastering-state-management-with-redux-toolkit-a-beginners-guide-39d65d0c2dd5?source=rss-215563e04d5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/39d65d0c2dd5</guid>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[redux-toolkit]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Ashan Perera]]></dc:creator>
            <pubDate>Sat, 15 Jun 2024 12:15:59 GMT</pubDate>
            <atom:updated>2024-06-15T12:15:59.566Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O0WtZnVZgeWsxZMWa_ZekQ.gif" /></figure><p>Redux is a powerful state management library commonly used in JavaScript applications, particularly with React. It helps manage the state of your application predictably, making it easier to develop and maintain complex applications. To understand Redux, it’s essential to grasp three fundamental concepts: the store, actions, and reducers.</p><h4>Store</h4><p>The <strong>store</strong> is the central place where the state of your entire application lives. It’s like a container holding the state tree, an object representing the current state of your app.</p><blockquote>Think of the store as the “brain” of your application, keeping track of all the data that various parts of your app need to function.</blockquote><h4>Actions</h4><p><strong>Actions</strong> are plain JavaScript objects that describe something that happened in the application. They are the only source of information for the store.</p><h4>Reducer</h4><p><strong>Reducers</strong> are pure functions that take the current state and an action as arguments and return a new state. They specify how the state should change in response to an action. A reducer function must be pure, meaning it should only depend on its input arguments and not cause any side effects.</p><p>In a Redux application, actions are dispatched to signal that something has happened, reducers handle these actions to update the state, and the store holds and manages the state. This flow ensures a predictable and consistent way to manage your application’s state, making it easier to understand, debug, and test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P9-w7VFBYIYUd0EFP7s1eg.png" /></figure><h3>Let’s Code</h3><p>First, create a ReactJS application using your preferred method. For this demo, a TypeScript application was created to demonstrate the necessary type declarations but this can be done in JavaScript applications without type declarations.</p><p>Then install the following two packages.</p><pre>npm install react-redux<br><br>npm install @reduxjs/toolkit</pre><p>Since using redux in its basic form is a bit difficult we are going to use Redux Toolkit which is a modern redux library that will make our life easier .It will do most of the groundwork for us which will release us from writing lots of boilerplate code.</p><h4>Create Redux Store</h4><p>First, create a store file inside the repository. Normally it will be located under the “<em>store/store.ts</em>”.</p><p>Next, build the template for the store.</p><pre>import { configureStore } from &quot;@reduxjs/toolkit&quot;;<br><br>export const store = configureStore({<br>    reducer: {}<br>})<br><br>export type RootState = ReturnType&lt;typeof store.getState&gt;<br>export type AppDispatch = typeof store.dispatch</pre><p>Here by utilizing the “<em>configureStore </em>”method from the Redux Toolkit the store is created and type declarations for both RootState and AppDispatch have been exported.</p><p>Later by constructing reducers, the type of the state and dispatch will automatically be changed.</p><p>Next, let&#39;s provide the state created by the store to the application so that values from the state can be read and actions can be dispatched inside the application globally.</p><p>In the “<em>main.tsx</em>” (or “<em>main.jsx</em>”) file wrap the entire application from the “<em>Redux Provider</em>”.</p><pre>import { Provider } from &quot;react-redux&quot;;<br>import { store } from &quot;./store/store.ts&quot;;<br><br>ReactDOM.createRoot(document.getElementById(&quot;root&quot;)!).render(<br>  &lt;React.StrictMode&gt;<br>    &lt;Provider store={store}&gt;<br>      &lt;App /&gt;<br>    &lt;/Provider&gt;<br>  &lt;/React.StrictMode&gt;<br>);</pre><p>This “<em>Provider </em>”will bind the store to the application and work with React Context API. Now the store is accessible to any component inside the “<em>&lt;App/&gt;</em>”.</p><h4>Create Slice</h4><p>Since this demo is focused on a counter application let&#39;s create a directory called “<em>counter</em>” inside the “<em>store</em>” directory to place everything related to the counter function.</p><p>Let&#39;s create a “<em>counterSlice.ts</em>” file.</p><pre>import { createSlice } from &quot;@reduxjs/toolkit&quot;;<br><br>interface CounterState {<br>  value: number;<br>}<br><br>const initialState: CounterState = {<br>  value: 0,<br>};<br><br>const counterSlice = createSlice({<br>  name: &quot;counter&quot;,<br>  initialState,<br>  reducers: {},<br>});<br><br>export default counterSlice.reducer;</pre><p>Since we are using TypeScript first thing to do is to define an interface called “<em>CounterState</em>” to define the shape and the types inside the object of the reducer. If you are using Javascript this is not needed.</p><p>Then “<em>initialState</em>” is defined. This is the starting value of the specific state.</p><p>After that, by invoking the “<em>createSlice</em>” function provided by Redux Toolkit we can create the “<em>couterSlice</em>” with parameters “<em>name</em>”, “<em>initialState</em>”, and “<em>reducers</em>”. For now, let&#39;s keep the “<em>reducers</em>” as an empty object.</p><p>Then the returning “<em>reducer</em>” from the “<em>counterSlice</em>” can be exported.</p><p>Finally, we can add this exporter reducer to the reducer object in the previously created store.</p><pre>import counterSlice from &quot;./counter/counterSlice&quot;;<br><br>export const store = configureStore({<br>  reducer: {<br>    counter: counterSlice,<br>  },<br>});</pre><p>Now our “<em>counterSlice</em>” is connected to the redux store which is accessible to the entire application through the “<em>Provider</em>”.</p><h4>Create Action and Reducers</h4><p>Now let&#39;s create a reducer that can increment the value of the slice by one.</p><p>First, add a new reducer called “<em>increment</em>” to the reducers object inside the “<em>counterSlice</em>”.</p><pre>const counterSlice = createSlice({<br>  name: &quot;counter&quot;,<br>  initialState,<br>  reducers: {<br>    increment: (state) =&gt; {<br>      state.value += 1;<br>    },<br>  },<br>});</pre><blockquote>Here you can see that the value is directly assigned to the state but normally a state cannot be mutated like this.</blockquote><blockquote>If we are using only redux then to make a change to a state first we need to make a copy of the current state do the change to the copy and replace the entire state to avoid state mutations.</blockquote><blockquote>But with Redux Toolkit we can write the code like this and Redux Toolkit will handle the state without mutation behind the scene.</blockquote><p>Then export the reducer as actions.</p><pre>export const { increment } = counterSlice.actions;</pre><p>Next in the react component, we need a mechanism to read the counter value from the store and a way to alter the value.</p><p>For now, let&#39;s build a simple UI with a button and a label to perform these two functions.</p><pre>import &quot;./App.css&quot;;<br>import { useDispatch, useSelector } from &quot;react-redux&quot;;<br>import { RootState } from &quot;./store/store&quot;;<br>import { increment } from &quot;./store/counter/counterSlice&quot;;<br><br>function App() {<br>  const count = useSelector((state: RootState) =&gt; state.counter.value);<br>  const dispatch = useDispatch();<br><br>  return (<br>    &lt;&gt;<br>      &lt;h1&gt;Redux Toolkit&lt;/h1&gt;<br>      &lt;h3&gt;{count}&lt;/h3&gt;<br>      &lt;button<br>        onClick={() =&gt; {<br>          dispatch(increment());<br>        }}<br>      &gt;<br>        Increment<br>      &lt;/button&gt;<br>    &lt;/&gt;<br>  );<br>}<br><br>export default App;</pre><p>Here “<em>useSelector</em>” is utilized to read the value from the store while using “<em>useDispatch</em>” to invoke the reducer that we exported as an action before.</p><h4>Actions with Arguments</h4><p>What if we want to send an argument in the action and based on that the state change should be performed?</p><p>For this we can utilize the second return value of a reducer which is the action and by reading its payload.</p><p>Let&#39;s create a new reducer called “<em>incrementByValue</em>”.</p><pre>incrementByValue: (state, action: PayloadAction&lt;number&gt;) =&gt; {<br>      state.value += action.payload;<br>    },</pre><p>As you can see there is a second parameter called action which will have a payload that can be used to conditionally alter the state.</p><p>Modified “<em>counterSlice.ts</em>” should look like this.</p><pre>import { PayloadAction, createSlice } from &quot;@reduxjs/toolkit&quot;;<br><br>interface CounterState {<br>  value: number;<br>}<br><br>const initialState: CounterState = {<br>  value: 0,<br>};<br><br>const counterSlice = createSlice({<br>  name: &quot;counter&quot;,<br>  initialState,<br>  reducers: {<br>    increment: (state) =&gt; {<br>      state.value += 1;<br>    },<br>    incrementByValue: (state, action: PayloadAction&lt;number&gt;) =&gt; {<br>      state.value += action.payload;<br>    },<br>  },<br>});<br><br>export const { increment, incrementByValue } = counterSlice.actions;<br><br>export default counterSlice.reducer;</pre><p>Then add another button to the UI invoking this action as follows.</p><pre>&lt;button<br>   onClick={() =&gt; {<br>     dispatch(incrementByValue(10));<br>   }}<br> &gt;<br>   Increment 10<br>&lt;/button&gt;</pre><h4>Asynchronous Actions</h4><p>In real-world applications sometimes we need actions to be asynchronous for tasks like fetching data from a backend. In these cases, action has to wait until the response comes and based on that response the state change happens.</p><p>For such implementations redux has a different action called “<em>async actions</em>”.</p><p>First, create an async action called “<em>incrementAsync</em>” as follows.</p><pre>export const incrementAsync = createAsyncThunk(<br>  &quot;counter/incrementAsync&quot;,<br>  async (value: number) =&gt; {<br>    // this is where actual request code goes<br>    await new Promise((resolve) =&gt; setTimeout(resolve, 3000));<br>    return value;<br>  }<br>);</pre><p>It&#39;s almost the same as the standard action but for async actions, we need to create an object using “<em>createAsyncThunk</em>” and pass the name “<em>counter/incrementAsync</em>” manually.</p><p>Then this object can be attached to the “<em>counterSlice</em>” with the use of the “<em>extraReducers</em>” argument in “<em>createSlice</em>” like below.</p><pre>const counterSlice = createSlice({<br>  name: &quot;counter&quot;,<br>  initialState,<br>  reducers: {<br>    increment: (state) =&gt; {<br>      state.value += 1;<br>    },<br>    incrementByValue: (state, action: PayloadAction&lt;number&gt;) =&gt; {<br>      state.value += action.payload;<br>    },<br>  },<br>  extraReducers: (builder) =&gt; {<br>    builder<br>      .addCase(incrementAsync.pending, () =&gt; {<br>        console.log(&quot;waiting for the response&quot;);<br>      })<br>      .addCase(<br>        incrementAsync.fulfilled,<br>        (state, action: PayloadAction&lt;number&gt;) =&gt; {<br>          state.value += action.payload;<br>        }<br>      );<br>  },<br>});</pre><p>Here as many cases can be attached to the builder object and in each object we can define a reducer.</p><p>But unlike standard actions, async actions have multiple states as you can see here the same “<em>incrementAsync</em>” action has been used to perform two reducers in two different states namely “<em>pending</em>” and “<em>fulfilled</em>”.</p><p>In order to dispatch async actions we need to add the types from our async actions to “<em>useDispatch</em>”.</p><pre>  const dispatch = useDispatch&lt;AppDispatch&gt;();</pre><p>Finally, we can use this inside our UI, and see this inaction.</p><pre>&lt;button<br>  onClick={() =&gt; {<br>    dispatch(incrementAsync(5));<br>  }}<br>&gt;<br>  IncrementAsync 5<br>&lt;/button&gt;</pre><p>Thats it! now you have all the building blocks to build anything using redux.</p><p>The complete project is publically available on my GitHub which you can access via the below link.</p><p><a href="https://github.com/AshanPerera98/Redux-ReactJS">GitHub - AshanPerera98/Redux-ReactJS</a></p><p>More information about the Redux Toolkit and its implementations can be found in the official documentation.</p><p><a href="https://redux-toolkit.js.org/">Redux Toolkit</a></p><p>Thank You!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39d65d0c2dd5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Singleton: Design Patterns with Java]]></title>
            <link>https://medium.com/@ashantiwankaperera/singleton-design-patterns-with-java-1b20c14a056a?source=rss-215563e04d5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b20c14a056a</guid>
            <category><![CDATA[singleton]]></category>
            <category><![CDATA[oop]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[creational-design-pattern]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Ashan Perera]]></dc:creator>
            <pubDate>Thu, 30 May 2024 03:04:42 GMT</pubDate>
            <atom:updated>2024-05-30T03:04:42.878Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vEg1sXi4UF0QAkw1VVWn_Q.png" /></figure><blockquote><strong>Singleton</strong> is a creational design pattern that lets you ensure that a class has only one instance while providing a global access point to this instance.</blockquote><p>This means in your code if you need to maintain something as a single instance and every time it is used this design pattern will return the initial instance and only if there is no available instance will it create a new instance.</p><p>A real-world application for this would be something like a database connection.</p><p>Every time the application needs to perform an action on the database we don&#39;t need to create a new connection (instance) to the database. it should only be initialized once and the existing connection should be used afterwards.</p><h3>Code</h3><p>Let&#39;s code this using Java.</p><pre>public class Singleton {<br>    private static Singleton instance;<br>    private String connectionString;<br>    private String password;<br>    <br>    private Singleton(String connectionString, String password){<br>        this.connectionString = connectionString;<br>        this.password = password;<br>    }<br>    <br>    public static Singleton getInstance(String connectionString, String password){<br>        if(instance==null){<br>            instance = new Singleton(connectionString, password);<br>        }<br>        <br>        return instance;<br>    }<br>}</pre><p>First the Singleton “<em>instance</em>” has been assigned as a private static.</p><p>Then following the encapsulation concept, required attributes can be added as private fields.</p><p>After that as encapsulation practices, we can create a constructor for the instance but the change here is we declare the constructor as <strong>private</strong> so it can only be accessible inside the class.</p><p>Finally, a public static method can be created to take the required variables as inputs and return an “<em>instance</em>”. Normally this method is named “<em>getInstance</em>”.</p><p>Inside the “<em>getInstance</em>” method, we can first check if there is an “<em>instance</em>” currently available and if so return the existing “<em>instance</em>”, if not create a new “<em>instance</em>” and return it.</p><p>This is the basis of the <strong>Singleton </strong>design pattern.</p><h3>Optimizations</h3><p>But there are a few problems. Because Java is capable of <strong>multithreading</strong> there can be two “<em>instances</em>” initializing parallelly. So we have to improve the code to handle it.</p><pre>public class Singleton {<br>    private static Singleton instance;<br>    private String connectionString;<br>    private String password;<br>    <br>    private Singleton(String connectionString, String password){<br>        this.connectionString = connectionString;<br>        this.password = password;<br>    }<br>    <br>    public static Singleton getInstance(String connectionString, String password){<br>        if(instance==null){<br>            synchronized (Singleton.class){<br>                if(instance==null){<br>                    instance = new Singleton(connectionString, password);<br>                }<br>            }<br>        }<br>        <br>        return instance;<br>    }<br>}</pre><p>Here by wrapping the whole “<em>instance</em>” creation inside <strong>synchronized</strong>, if an instance is created it will be shared across all the threads.</p><p>This leads to another problem which is while the first thread is creating the “<em>instance</em>” and the second thread tries to access the “<em>instance</em>” it will be forced to access an incomplete “<em>instance</em>” which can lead to an application crash.</p><p>This can be easily eliminated by adding a <strong>volatile</strong> modifier to the “<em>instance</em>”.</p><p>With that change and some micro enhancements, the final code should look like this.</p><pre>public class Singleton {<br>    private static volatile Singleton instance;<br>    private String connectionString;<br>    private String password;<br>    <br>    private Singleton(String connectionString, String password){<br>        this.connectionString = connectionString;<br>        this.password = password;<br>    }<br>    <br>    public static Singleton getInstance(String connectionString, String password){<br>        Singleton result = instance;<br>        <br>        if(result==null){<br>            synchronized (Singleton.class){<br>                result = instance;<br>                if(result==null){<br>                    instance = result = new Singleton(connectionString, password);<br>                }<br>            }<br>        }<br>        <br>        return result;<br>    }<br>}</pre><p>More about Singleton and other design patterns can be found in the following link.</p><p><a href="https://refactoring.guru/design-patterns/singleton">Singleton</a></p><p>Thank You!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b20c14a056a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>