<?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 Russell Peiris on Medium]]></title>
        <description><![CDATA[Stories by Russell Peiris on Medium]]></description>
        <link>https://medium.com/@ardpeiris?source=rss-4ba34c58f429------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Y195CLBfY4osPdf7--oUvw.jpeg</url>
            <title>Stories by Russell Peiris on Medium</title>
            <link>https://medium.com/@ardpeiris?source=rss-4ba34c58f429------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 08:26:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ardpeiris/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[Optimizing a React Component with React.memo and useMemo()]]></title>
            <link>https://medium.com/@ardpeiris/optmizing-a-react-component-with-react-memo-and-usememo-4bf639170ee8?source=rss-4ba34c58f429------2</link>
            <guid isPermaLink="false">https://medium.com/p/4bf639170ee8</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[usememo]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[memoization]]></category>
            <dc:creator><![CDATA[Russell Peiris]]></dc:creator>
            <pubDate>Wed, 05 Feb 2025 12:24:57 GMT</pubDate>
            <atom:updated>2025-02-05T12:25:25.058Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kHt9DY5YUddP8n4d3pjkVg.png" /><figcaption>React Memoization</figcaption></figure><p>Let’s look at this react component. UserList is a component that will render a list of users by taking the users array as a prop. The <strong>users array</strong> in the App component is passed down to the <strong>users prop</strong> in the UserList.</p><pre>import React, { useState } from &quot;react&quot;;<br><br>const UserList = ({ users }) =&gt; {<br>  return (<br>    &lt;ul&gt;<br>      {users.map((user) =&gt; (<br>        &lt;li key={user.id}&gt;{user.name}&lt;/li&gt;<br>      ))}<br>    &lt;/ul&gt;<br>  );<br>};<br><br>export default function App() {<br>  const [count, setCount] = useState(0);<br>  const users = [<br>    { id: 1, name: &quot;Alice&quot; },<br>    { id: 2, name: &quot;Bob&quot; },<br>  ];<br><br>  return (<br>    &lt;div&gt;<br>      &lt;button onClick={() =&gt; setCount(count + 1)}&gt;Increment: {count}&lt;/button&gt;<br>      &lt;UserList users={users} /&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Though everything seems to look okay, under the hood unnessary re-renders happen. Here’s how</p><ol><li>When you click the button, the count state increments, triggering a re-render of the App component. Since the users array is defined inside App, it gets recreated as a new object in memory on every render.</li><li>Because arrays and objects are <strong>reference types</strong>, even if their contents remain the same, a new reference is created.</li><li>React performs a <strong>shallow comparison</strong> of props and detects this new reference, leading to an unnecessary re-render of the UserList component.</li></ol><p>This is where you have to use <strong>memoization</strong>.</p><blockquote><a href="https://www.geeksforgeeks.org/what-is-memoization-in-react/#:~:text=05%20Apr%2C%202024-,Memoization%20is%20a%20powerful%20optimization%20technique%20used%20in%20React%20to%20improve%20the%20performance%20of%20applications%20by%20caching%20the%20results%20of%20expensive%20function%20calls%20and%20returning%20the%20cached%20result%20when%20the%20same%20inputs%20occur%20again.,-In%20this%20article">Memoization is a powerful optimization technique used in React to improve the performance of applications by caching the results of expensive function calls and returning the cached result when the same inputs occur again</a>.</blockquote><p>React offers useMemo hook and React.memo for this purpose.<br>useMemo is a React Hook that lets you cache the result of a calculation between re-renders. memo lets you skip re-rendering a component when its props are unchanged.</p><p>Let’s look at the updated code:</p><pre>import React, { useState, useMemo } from &quot;react&quot;;<br><br>// ✅ Memoizing the component to prevent unnecessary re-renders<br>const UserList = React.memo(({ users }) =&gt; {<br>  console.log(&quot;UserList re-rendered&quot;);<br>  return (<br>    &lt;ul&gt;<br>      {users.map((user) =&gt; (<br>        &lt;li key={user.id}&gt;{user.name}&lt;/li&gt;<br>      ))}<br>    &lt;/ul&gt;<br>  );<br>});<br><br>export default function App() {<br>  const [count, setCount] = useState(0);<br><br>  // ✅ Memoizing users to prevent re-creation on each render<br>  const users = useMemo(() =&gt; [<br>    { id: 1, name: &quot;Alice&quot; },<br>    { id: 2, name: &quot;Bob&quot; },<br>  ], []);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;button onClick={() =&gt; setCount(count + 1)}&gt;Increment: {count}&lt;/button&gt;<br>      &lt;UserList users={users} /&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><h3>What was fixed?</h3><ol><li>Used <strong>React.memo() </strong>for<strong> </strong><strong>UserList</strong></li></ol><ul><li>Prevents unnecessary re-renders when users prop hasn’t changed.</li></ul><p>2. Wrapped<strong> </strong><strong>users </strong>array with <strong>useMemo()</strong></p><ul><li>Without useMemo(), users is recreated on every render, causing UserList to re-render unnecessarily.</li></ul><h3>Before Optimization</h3><p>UserList re-renders even when count changes, because users is recreated every time.</p><h3>After Optimization</h3><p>UserList only re-renders when users actually change.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4bf639170ee8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Breaking Encapsulation: How Mutable Objects Can Compromise Your Code]]></title>
            <link>https://medium.com/@ardpeiris/breaking-encapsulation-how-mutable-objects-can-compromise-your-code-898b2a8a3f05?source=rss-4ba34c58f429------2</link>
            <guid isPermaLink="false">https://medium.com/p/898b2a8a3f05</guid>
            <category><![CDATA[oop]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[mutable-objects]]></category>
            <category><![CDATA[encapsulation]]></category>
            <dc:creator><![CDATA[Russell Peiris]]></dc:creator>
            <pubDate>Sun, 12 Jan 2025 19:57:17 GMT</pubDate>
            <atom:updated>2025-01-13T04:30:24.434Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*u7LqzgsaXxNMtetslC09kA.png" /><figcaption>Broken Capsule</figcaption></figure><p>To fully understand the context, lets first understand what Encapsulation is!</p><p>Encapsulation refers to the practice of hiding an object’s internal state and requiring all interactions to be performed through controlled methods.</p><p>We do this to protect the internal state of objects and ensure controlled access.</p><p>Some of you might still not understand this, so lets look at this Employee class.</p><p><strong>Note</strong>: The java.util.Date class used in this example is considered outdated and is included here solely for demonstration purposes to illustrate the concept of mutability and its impact on encapsulation.</p><pre>import java.util.Date;<br><br>public class Employee {<br>    private String name;<br>    private double salary;<br>    private Date joinedDate; // Mutable field<br><br>    public Employee(String name, double salary, Date joinedDate) {<br>        this.name = name;<br>        this.salary = salary;<br>        this.joinedDate = joinedDate;<br>    }<br><br>    public String getName() {<br>        return name;<br>    }<br><br>    public void setName(String name) {<br>        this.name = name;<br>    }<br><br>    public double getSalary() {<br>        return salary;<br>    }<br><br>    public void setSalary(double salary) {<br>        this.salary = salary;<br>    }<br><br>    public Date getJoinedDate() {<br>        return joinedDate;<br>    }<br><br>    public void setJoinedDate(Date joinedDate) {<br>        this.joinedDate = joinedDate;<br>    }<br>}</pre><h3>1. Private Fields:</h3><ul><li>The fields name, salary, and joinedDate are marked as private. This means these fields cannot be directly accessed or modified from outside the Employee class.</li></ul><pre>Employee emp = new Employee(&quot;Alice&quot;, 50000, new Date());<br>// Direct access like emp.name = &quot;Bob&quot;; is not allowed.</pre><h3>2. Public Getter and Setter Methods:</h3><ul><li>Public methods (getName, setName, getSalary, setSalary, getJoinedDate, setJoinedDate) are provided to read or modify the private fields. These methods act as controlled access points.</li></ul><pre>emp.setName(&quot;Bob&quot;); // Allowed<br>System.out.println(emp.getName()); // Allowed</pre><h3>3. Controlled Access</h3><ul><li>By using getter and setter methods, you can impose restrictions or add <strong>validations </strong>when accessing or modifying the fields.</li><li>This is a <strong>benefit </strong>of encapsulation. It allows you to change the internal implementation without affecting any code other than the specific method.</li><li>For example, you can modify the setSalary method to prevent setting negative salaries.</li></ul><pre>public void setSalary(double salary) {<br>    if (salary &gt;= 0) { <br>        this.salary = salary;<br>    } else {<br>        throw new IllegalArgumentException(&quot;Salary must be positive&quot;);<br>    }<br>}</pre><h3>The Problem: Mutable Objects Break Encapsulation</h3><p>Mutable means liable to change.</p><p>A <strong>mutable object</strong> can have its state changed after creation. The Date class in Java is a prime example.</p><p>Let’s understand how the above implementation of Employee class has been compromised.</p><pre>public class Main {<br>    public static void main(String[] args) {<br>        // Create an Employee object<br>        Date date = new Date();<br>        Employee employee = new Employee(&quot;Alice&quot;, 50000, date);<br><br>        // Get the joinedDate<br>        Date culpritDateObject = employee.getJoinedDate();<br>        culpritDateObject.setTime(0); // Modifies the date to &quot;Thu Jan 01 00:00:00 GMT 1970&quot;<br><br>        // Check the Employee&#39;s joinedDate<br>        System.out.println(&quot;Employee&#39;s joinedDate: &quot; + employee.getJoinedDate());<br>    }<br>}<br><br>Output: Employee&#39;s joinedDate: Thu Jan 01 00:00:00 GMT 1970</pre><p>Note that you were able to modify a private property <em>joinedDate </em>without using the <em>setJoinedDate(“..a date..”)</em> method simply using the setTime() method in the mutable object instance <em>culpritDateObject.</em></p><p>One might argue “How does modifying culpritDateObject change the value of private joinedDate?”</p><p>When you deal with objects, you&#39;re working with <strong>references</strong> to those objects. These references point to the memory location where the actual object is stored.</p><p>Let me help you understand,<br>1. <strong>Primitive Types</strong>: For variables of primitive types (like int, float, etc.), the variable directly holds the value.</p><pre>int a = 10;  // `a` holds the value 10</pre><p><strong>2. Reference Types (Objects)</strong>: For variables of object types, the variable holds a <strong>reference</strong> to the memory location of the object.</p><pre>Date date = new Date(); // `date` holds a reference to the memory location of the Date object</pre><p>So in this Employee class example, when you use a getter method, you’re essentially returning reference of the date object, not the value of the date itself.</p><p>Breaking it down further:</p><ul><li>A new Date object is created in heap memory when new Date() is called.</li><li>A new Employee object is created in heap memory with its joinedDate field <strong>pointing </strong>to the same Date object.</li><li>The getJoinedDate() directly returns the reference to the Date object stored in the joinedDate field.</li><li>When culpritDateObject.setTime(0) is called, it modifies the <strong>Date object</strong> in heap memory.</li><li>Since both employee.joinedDate and culpritDateObject point to the same object in heap memory, the modification is reflected in both references.</li></ul><p>As a result <em>culpritDateObject </em>access the same memory location as<em> joinedDate </em>allowing it to be modified.</p><h4>What Happened?</h4><ul><li>The getter getJoinedDate() returned a <strong>reference</strong> to the internal joinedDate object.</li><li>Modifying the returned Date object directly affected the internal state of the Employee object.</li><li><strong>Encapsulation is broken</strong> because external code modified the internal state.</li></ul><h3>The Solution: Defensive Copying</h3><h4>1. What is Defensive Copying?</h4><p>Defensive copying ensures that only a copy of a mutable object is returned or accepted, preserving the original object’s integrity.</p><p>Modify the Employee class as follows:</p><pre>public class Employee {<br>    private String name;<br>    private double salary;<br>    private Date joinedDate;<br><br>    public Employee(String name, double salary, Date joinedDate) {<br>        this.name = name;<br>        this.salary = salary;<br>        this.joinedDate = new Date(joinedDate.getTime()); // Copy on assignment<br>    }<br><br>    public Date getJoinedDate() {<br>        return new Date(joinedDate.getTime()); // Return a defensive copy<br>    }<br><br>    public void setJoinedDate(Date joinedDate) {<br>        this.joinedDate = new Date(joinedDate.getTime()); // Copy on setting<br>    }<br>}</pre><h3><strong>2. Use Immutable Objects</strong></h3><p>Replace mutable classes like Date with immutable alternatives like LocalDate (from java.time)</p><pre>private LocalDate joinedDate;</pre><h3>Conclusion</h3><ul><li>Encapsulation is a cornerstone of robust object-oriented design.</li><li>Mutable objects, if mishandled, can silently break encapsulation, leading to bugs and unpredictable behavior.</li><li>By using defensive copying and immutable objects, you can protect your class’s internal state and ensure long-term code reliability.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=898b2a8a3f05" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>