<?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 Kalindu Sudaraka on Medium]]></title>
        <description><![CDATA[Stories by Kalindu Sudaraka on Medium]]></description>
        <link>https://medium.com/@sudarakakalindu20?source=rss-9fbc2d3b538e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*WnvXJQMnONauak6Z</url>
            <title>Stories by Kalindu Sudaraka on Medium</title>
            <link>https://medium.com/@sudarakakalindu20?source=rss-9fbc2d3b538e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 06:12:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sudarakakalindu20/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[Mastering SOLID Principles: The Key to Clean and Scalable Code]]></title>
            <link>https://medium.com/@sudarakakalindu20/mastering-solid-principles-the-key-to-clean-and-scalable-code-151bf643b07a?source=rss-9fbc2d3b538e------2</link>
            <guid isPermaLink="false">https://medium.com/p/151bf643b07a</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[solid-principles]]></category>
            <category><![CDATA[guidelines]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Kalindu Sudaraka]]></dc:creator>
            <pubDate>Tue, 24 Dec 2024 21:49:59 GMT</pubDate>
            <atom:updated>2024-12-25T04:42:20.711Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9_NOky6OPgeK1sOcyy6aXQ.png" /></figure><p><strong>What is SOLID Principles?</strong></p><p>The <strong>SOLID principles</strong> are a set of guidelines for writing clean, maintainable, and scalable code in object-oriented programming. These principles help developers design software that is easier to understand, modify, and extend without breaking existing functionality.</p><p><strong>Why Use SOLID Principles?</strong></p><p>💎 Improve Code Quality:</p><ul><li>Makes code easier to read, test, and debug.</li></ul><p>💎 Enhance Flexibility:</p><ul><li>Allows adding new features without changing existing code.</li></ul><p>💎 Reduce Complexity:</p><ul><li>Simplifies design and reduces dependencies between components.</li></ul><p>💎 Facilitate Maintenance:</p><ul><li>Reduces the risk of bugs when modifying or extending the application.</li></ul><p>💎 Promote Reusability:</p><ul><li>Encourages the creation of reusable components that can be applied to different parts of the application or other projects.</li></ul><p><strong>Where Are They Used?</strong></p><p>💎 Object-Oriented Programming (OOP):</p><ul><li>Helps structure OOP-based projects like in <strong>Java</strong>, <strong>C#</strong>, or <strong>Python</strong>.</li></ul><p>💎 Software Development Projects:</p><ul><li>Used in large-scale enterprise applications to manage complexity.</li></ul><p>💎 Team Collaboration:</p><ul><li>Ensures consistency and reduces confusion when multiple developers work on the same codebase.</li></ul><p>💎 Agile Development:</p><ul><li>Supports iterative development by allowing quick modifications without disrupting the system.</li></ul><p><strong>Solid Principles are</strong></p><p>S — Single Responsibility Principle (SRP)<br>O — Open/Closed Principle<br>L — Liskov’s Substitution Principle (LSP)<br>I — Interface Segregation Principle (ISP)<br>D — Dependency Inversion Principle (DIP)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*S5QV4n3GwtWeces9OT_iWA.png" /></figure><ol><li><strong>S — Single Responsibility Principle (SRP)</strong></li></ol><p>A function, class, or module should have a single, well-defined responsibility, focusing exclusively on one specific task or functionality. This ensures clarity, maintainability, and reduces the risk of unintended side effects when modifications are made.</p><p>Example (Violation)</p><pre>class Report {<br>    public void generateReport() { /* Generates the report */ }<br>    public void printReport() { /* Prints the report */ }<br>}<br><br>//Here, the Report class handles both generating and printing, violating SRP</pre><p>Fixed</p><pre>class ReportGenerator {<br>    public void generateReport() { /* Generates the report */ }<br>}<br><br>class ReportPrinter {<br>    public void printReport() { /* Prints the report */ }<br>}<br>//Now, each class has a single responsibility</pre><p><strong>Why It’s Important:</strong><br> Having a class responsible for only one task makes your code <strong>easier to understand, debug, and maintain</strong>. When a class does too many things, changing one responsibility might unintentionally affect the others.</p><p><strong>Example:</strong><br> Imagine a “UserManager” class that handles both user authentication and database operations. If you modify the authentication logic, it might break the database code. Separating these responsibilities ensures changes in one area don’t ripple into others.</p><p><strong>2. O</strong> <strong>— Open/Closed Principle (OCP)</strong></p><p>A class should be open for extension but closed for modification it means a class should allow new functionality to be added without changing its existing code. This means you can extend its behavior by adding new code, but you shouldn’t modify the original code, ensuring stability and reducing the risk of introducing bugs.</p><p>Example (Violation)</p><pre>class Shape {<br>    public void drawCircle() { /* Draw a circle */ }<br>    public void drawSquare() { /* Draw a square */ }<br>}<br>//If a new shape is added (e.g., Triangle), we need to modify the Shape class</pre><p>Fixed</p><pre>abstract class Shape {<br>    public abstract void draw();<br>}<br><br>class Circle extends Shape {<br>    public void draw() { /* Draw a circle */ }<br>}<br><br>class Square extends Shape {<br>    public void draw() { /* Draw a square */ }<br>}<br>//Now, adding a new shape (e.g., Triangle) doesn&#39;t require modifying the existing code</pre><p><strong>Why It’s Important:</strong><br> When your code is open to extension but closed to modification, you can add new features without breaking existing functionality. This reduces bugs and regression when your application evolves.</p><p><strong>Example:</strong><br> In a billing system, if new payment methods (e.g., PayPal, Stripe) need to be added, you should be able to do this by creating new classes rather than editing the existing PaymentProcessor class. This ensures existing payment methods (e.g., CreditCard) remain unaffected.</p><h4><strong>3.</strong> L<strong> — Liskov Substitution Principle (LSP)</strong></h4><p>A subclass should function as a drop-in replacement for its parent class without altering the expected behavior of the application. This aligns with the <strong>Liskov Substitution Principle (LSP)</strong>, which states that objects of a subclass should be substitutable for objects of the parent class without affecting the correctness of the program. In simpler terms, the subclass should not impact or modify the existing behavior defined by the parent class.</p><p>Example (Violation)</p><pre>class Bird {<br>    public void fly() { /* Fly logic */ }<br>}<br><br>class Penguin extends Bird {<br>    public void fly() {<br>        throw new UnsupportedOperationException(&quot;Penguins can&#39;t fly!&quot;);<br>    }<br>}<br>//The subclass violates LSP because a Penguin cannot behave like a Bird</pre><p>Fixed</p><pre>abstract class Bird {<br>    public abstract void move();<br>}<br><br>class FlyingBird extends Bird {<br>    public void move() { /* Fly logic */ }<br>}<br><br>class Penguin extends Bird {<br>    public void move() { /* Swim logic */ }<br>}<br>//Here, Penguin overrides move() logically, preserving behavior</pre><p><strong>Why It’s Important:</strong><br> This principle ensures that your application remains <strong>flexible and bug-free</strong> when using inheritance. Substitutable subclasses make your code more reusable and avoid unexpected behavior.</p><p><strong>Example:</strong><br> If a Rectangle class has a method to set width and height, and a Square subclass changes this behavior to set both dimensions at once, it might break functionality in methods expecting a standard rectangle. Following LSP prevents such issues.</p><p><strong>4. I — Interface Segregation Principle (ISP)</strong></p><p>A class shouldn’t be forced to implement interfaces it doesn’t use it means that a class should only implement the methods it actually needs. In other words, no class should be forced to depend on methods it doesn’t use. Instead of having one large interface, it’s better to create smaller, more specific interfaces tailored to the needs of different classes.</p><p>Example (Violation)</p><pre>interface Worker {<br>    void code();<br>    void test();<br>}<br><br>class Developer implements Worker {<br>    public void code() { /* Coding */ }<br>    public void test() { /* Not applicable */ }<br>}<br>//The Developer is forced to implement test() even if it doesn&#39;t apply</pre><p>Fixed</p><pre>interface Coder {<br>    void code();<br>}<br><br>interface Tester {<br>    void test();<br>}<br><br>class Developer implements Coder {<br>    public void code() { /* Coding */ }<br>}<br><br>class QAEngineer implements Tester {<br>    public void test() { /* Testing */ }<br>}<br>//Separate interfaces ensure no unnecessary methods are implemented</pre><p><strong>Why It’s Important:</strong><br> This principle prevents <strong>unnecessary dependencies</strong> and ensures that classes only use methods relevant to them. It reduces the need for code updates when interfaces change, improving modularity.</p><p><strong>Example:</strong><br> If a large Employee interface has methods like code(), test(), and design(), a tester would still have to implement irrelevant methods like code(). Splitting these into smaller, focused interfaces avoids this problem.</p><p><strong>5.</strong> D<strong> — Dependency Inversion Principle (DIP)</strong></p><p>High-level modules shouldn’t depend on low-level modules. Both should depend on abstractions its mean the Dependency Inversion Principle states that high-level modules (the overall logic or policies) should not depend on low-level modules (detailed implementations). Instead, both should depend on abstractions (like interfaces). This makes the system flexible and easier to maintain since you can change low-level details without affecting high-level logic.</p><p>Example (Violation)</p><pre>class Light {<br>    public void turnOn() { /* Turns on the light */ }<br>}<br><br>class Switch {<br>    private Light light;<br><br>    public Switch() {<br>        this.light = new Light(); // Direct dependency<br>    }<br><br>    public void toggle() {<br>        light.turnOn();<br>    }<br>}<br>//The Switch depends directly on the Light class, making it harder to extend or test</pre><p>Fixed</p><pre>interface Device {<br>    void turnOn();<br>}<br><br>class Light implements Device {<br>    public void turnOn() { /* Turns on the light */ }<br>}<br><br>class Switch {<br>    private Device device;<br><br>    public Switch(Device device) {<br>        this.device = device; // Depends on abstraction<br>    }<br><br>    public void toggle() {<br>        device.turnOn();<br>    }<br>}<br>//Now, Switch can work with any Device that implements the Device interface</pre><p><strong>Why It’s Important:</strong><br> This principle makes code more <strong>flexible and easier to test</strong> by removing direct dependencies on specific implementations. Instead, depending on abstractions makes it easier to replace or modify components without breaking the code.</p><p><strong>Example:</strong><br> A NotificationService class directly depending on an EmailService class makes it hard to switch to a SMSService. By depending on a Notification interface, you can plug in any service (email, SMS, etc.) without modifying the core class.</p><p><strong>Conclusion</strong></p><p>In conclusion, understanding and applying the SOLID principles can greatly enhance the design and maintainability of your software. By focusing on creating more modular, flexible, and scalable systems, you’ll be able to write code that is easier to manage, extend, and test. Whether you’re working on small-scale projects or large, complex systems, incorporating SOLID principles can lead to better code quality and fewer headaches in the long run.</p><p>Remember, the goal of SOLID isn’t just to follow a set of rules — it’s about fostering a mindset that values simplicity, clarity, and adaptability. As you continue your software development journey, make sure to keep these principles in mind to build software that stands the test of time.</p><p>Happy coding!😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=151bf643b07a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering the Factory Pattern: A Key to Scalable and Maintainable Code]]></title>
            <link>https://medium.com/@sudarakakalindu20/mastering-the-factory-pattern-a-key-to-scalable-and-maintainable-code-dac87b36e71d?source=rss-9fbc2d3b538e------2</link>
            <guid isPermaLink="false">https://medium.com/p/dac87b36e71d</guid>
            <category><![CDATA[low-level-design]]></category>
            <category><![CDATA[design-pattern-in-java]]></category>
            <category><![CDATA[factory-pattern]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Kalindu Sudaraka]]></dc:creator>
            <pubDate>Sun, 10 Nov 2024 07:53:25 GMT</pubDate>
            <atom:updated>2024-11-10T07:53:25.121Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OA6xaTXS7LtD-ScZbC6wBw.png" /></figure><p>The Factory Pattern is a design pattern used in object-oriented programming to create objects without needing to specify the exact class of the object being created. Instead, it delegates the task of creating objects to a separate factory class, which decides which specific object to create based on input or configuration.</p><p>In the Factory Method pattern, objects are not created directly in the client code. Instead, the responsibility of creating objects is moved to a separate factory method, often within a factory class or a subclass, which determines and returns the appropriate object type.</p><h3><strong>Purpose of the Factory Pattern</strong></h3><p>The main purpose of the Factory Pattern is to simplify and centralize object creation. Instead of directly instantiating classes (e.g., new Car()), you call a method from a factory class (e.g., CarFactory.createCar()), which will return the right type of Car object for you. This approach makes the code easier to manage, especially when adding or changing types of objects because the creation logic is in one place.</p><h3><strong>Components of the factory Pattern</strong></h3><p>To understand the Factory Pattern, it’s helpful to look at its key components and how they work together. In the Factory Pattern, these components play specific roles that help separate object creation from the main code logic. Here are the main components:</p><p><strong>💎 Product</strong>: An interface or abstract class that defines the contract for objects the factory will create. It ensures that all product types have a consistent structure and behavior.</p><pre>//The Car interface defines the methods that all car types should implement.<br><br>// Car Interface<br>interface Car {<br>    void drive();<br>}</pre><p><strong>💎 ConcreteProduct</strong>: Specific implementations of the Product that represent various types the factory can produce. Each concrete class provides a unique version of the product.</p><pre>//These are the specific car types that implement the Car interface. Each class provides a unique implementation for the drive method.<br><br>// Concrete Car Classes<br>class SUV implements Car {<br>    public void drive() {<br>        System.out.println(&quot;Driving an SUV&quot;);<br>    }<br>} <br><br>class Sedan implements Car {<br>    public void drive() {<br>        System.out.println(&quot;Driving a Sedan&quot;);<br>    }<br>}<br><br>class Truck implements Car {<br>    public void drive() {<br>        System.out.println(&quot;Driving a Truck&quot;);<br>    }<br>}</pre><p><strong>💎 Factory</strong>: The creator class that contains the logic for creating and returning instances of ConcreteProduct based on input. It abstracts and centralizes object creation.</p><pre>//The CarFactory class is responsible for creating and returning instances of the specific car types. It has a factory method, createCar, which takes a carType string as input and returns the appropriate Car object.<br><br>// Factory Class<br>class CarFactory {<br>    // Factory method to create a car based on input<br>    public static Car createCar(String carType) {<br>        switch (carType) {<br>            case &quot;SUV&quot;:<br>                return new SUV();<br>            case &quot;Sedan&quot;:<br>                return new Sedan();<br>            case &quot;Truck&quot;:<br>                return new Truck();<br>            default:<br>                throw new IllegalArgumentException(&quot;Unknown car type&quot;);<br>        }<br>    }<br>}</pre><p><strong>💎 Client</strong>: The code that uses the factory to obtain Product instances without needing to know the specific types. This keeps the client code flexible and independent from concrete implementations.</p><pre>// The Main class is the client that requests specific car instances from the factory. It doesn’t know the details of the car creation process; it only interacts with the factory to get the desired Car objects.<br><br>// Client Code<br>public class Main {<br>    public static void main(String[] args) {<br>        // Client code asks the factory for the specific car type<br>        Car mySUV = CarFactory.createCar(&quot;SUV&quot;);<br>        Car mySedan = CarFactory.createCar(&quot;Sedan&quot;);<br>        Car myTruck = CarFactory.createCar(&quot;Truck&quot;);<br><br>        // Each car is created by the factory, so the client code doesn’t know the details<br>        mySUV.drive();   // Outputs: Driving an SUV<br>        mySedan.drive(); // Outputs: Driving a Sedan<br>        myTruck.drive(); // Outputs: Driving a Truck<br>    }<br>}<br><br></pre><h3><strong>Decoupling Object Creation from the Main Code</strong></h3><p>The Factory Pattern helps keep your main code separate from the details of object creation. Here’s how it works,</p><p>To understand how the Factory Pattern helps decouple object creation from the main code, let’s look at an example in Java. We’ll compare code <strong>without the Factory Pattern</strong> and <strong>with the Factory Pattern</strong>.</p><p><strong>👍 Without the Factory Pattern</strong></p><pre>// Car Interface<br>interface Car {<br>    void drive();<br>}<br><br>// Concrete Car Classes<br>class SUV implements Car {<br>    public void drive() {<br>        System.out.println(&quot;Driving an SUV&quot;);<br>    }<br>}<br><br>class Sedan implements Car {<br>    public void drive() {<br>        System.out.println(&quot;Driving a Sedan&quot;);<br>    }<br>}<br><br>class Truck implements Car {<br>    public void drive() {<br>        System.out.println(&quot;Driving a Truck&quot;);<br>    }<br>}<br><br>// Client Code<br>public class Main {<br>    public static void main(String[] args) {<br>        // The main code directly creates specific car types<br>        Car mySUV = new SUV();<br>        Car mySedan = new Sedan();<br>        Car myTruck = new Truck();<br>        <br>        // Each car must be created and used separately<br>        mySUV.drive();   // Outputs: Driving an SUV<br>        mySedan.drive(); // Outputs: Driving a Sedan<br>        myTruck.drive(); // Outputs: Driving a Truck<br>    }<br>}</pre><p>In this setup, the Main class is directly responsible for creating each car type. If we want to add or change car types later (e.g., add an ElectricCar), we would have to modify the main code to include this new type. This creates a dependency between the client code and specific car classes, making the code harder to maintain.</p><p><strong>👍 With the Factory Pattern</strong></p><pre>// Car Interface<br>interface Car {<br>    void drive();<br>}<br><br>// Concrete Car Classes<br>class SUV implements Car {<br>    public void drive() {<br>        System.out.println(&quot;Driving an SUV&quot;);<br>    }<br>}<br><br>class Sedan implements Car {<br>    public void drive() {<br>        System.out.println(&quot;Driving a Sedan&quot;);<br>    }<br>}<br><br>class Truck implements Car {<br>    public void drive() {<br>        System.out.println(&quot;Driving a Truck&quot;);<br>    }<br>}<br><br>// Factory Class<br>class CarFactory {<br>    // Factory method to create a car based on input<br>    public static Car createCar(String carType) {<br>        switch (carType) {<br>            case &quot;SUV&quot;:<br>                return new SUV();<br>            case &quot;Sedan&quot;:<br>                return new Sedan();<br>            case &quot;Truck&quot;:<br>                return new Truck();<br>            default:<br>                throw new IllegalArgumentException(&quot;Unknown car type&quot;);<br>        }<br>    }<br>}<br><br>// Client Code<br>public class Main {<br>    public static void main(String[] args) {<br>        // Client code asks the factory for the specific car type<br>        Car mySUV = CarFactory.createCar(&quot;SUV&quot;);<br>        Car mySedan = CarFactory.createCar(&quot;Sedan&quot;);<br>        Car myTruck = CarFactory.createCar(&quot;Truck&quot;);<br><br>        // Each car is created by the factory, so the client code doesn’t know the details<br>        mySUV.drive();   // Outputs: Driving an SUV<br>        mySedan.drive(); // Outputs: Driving a Sedan<br>        myTruck.drive(); // Outputs: Driving a Truck<br>    }<br>}</pre><p>By using the Factory Pattern, we’ve decoupled the object creation process from the main code, making the application more flexible and scalable.</p><h3>Pros and Cons of the Factory Pattern</h3><h3><strong>Pros</strong></h3><p><strong>💎 Decouples Code</strong>: Separates object creation from the main code, making it easier to manage and maintain.</p><p><strong>💎 Increased Flexibility</strong>: Allows new object types to be added without changing client code.</p><p><strong>💎 Improved Code Reusability</strong>: Centralizes creation logic, which can be reused across the application.</p><p><strong>💎 Encapsulates Object Creation</strong>: Reduces complexity for the client, as it doesn’t need to know the details of each object type.</p><h3><strong>Cons</strong></h3><p><strong>💎 More Classes</strong>: Introduces additional classes, which can increase code complexity.</p><p><strong>💎 Limited by Interface</strong>: All objects created must adhere to a common interface, which might restrict flexibility.</p><p><strong>💎 Overhead in Simple Applications</strong>: Can be overkill for small projects or cases with limited object types.</p><p><strong>💎 Less Transparent Code</strong>: Hides concrete class instantiation, which can make the code less readable for new developers.</p><h3>Conclusion</h3><p>In conclusion, the Factory Pattern is a powerful design pattern that simplifies object creation and promotes flexibility and maintainability in object-oriented systems. By decoupling the object creation process from the client code, the Factory Pattern allows developers to add new product types without modifying existing code, making the system more scalable.</p><p>In the example we used, the `CarFactory` class handles the creation of different car types like `SUV`, `Sedan`, and `Truck`. The client code only interacts with the factory to obtain a `Car` instance, without worrying about the specific implementation details of each car type. This keeps the client code clean and focused on its primary tasks, while the factory manages the complexity of object creation.</p><p>Overall, the Factory Pattern is an essential tool for building flexible, extensible applications, especially when the exact type of object is determined at runtime.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Be7ewXKHE06_hUOIOj5eQ.jpeg" /></figure><p>Thank you for reading! I hope this article helped you understand the Factory Pattern and its benefits. Stay tuned for more in our Design Patterns series. Until next time, happy coding! 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dac87b36e71d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JPA vs Hibernate: Choosing the Right Tool for Java Database Management]]></title>
            <link>https://medium.com/@sudarakakalindu20/jpa-vs-hibernate-choosing-the-right-tool-for-java-database-management-b8aa28d502b0?source=rss-9fbc2d3b538e------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8aa28d502b0</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[jpa]]></category>
            <category><![CDATA[hibernate]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[database-management]]></category>
            <dc:creator><![CDATA[Kalindu Sudaraka]]></dc:creator>
            <pubDate>Thu, 17 Oct 2024 06:07:20 GMT</pubDate>
            <atom:updated>2024-10-17T06:07:20.349Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vB1tA_w4T9CsxGB2obC59w.png" /></figure><h3><strong>Introduction</strong></h3><p>Database management is essential in Java application development. To build scalable and reliable apps, developers use tools like JPA (Java Persistence API) and Hibernate to simplify database interactions. These tools reduce the need for manual SQL and offer an object-oriented way to manage data, making the code cleaner and easier to maintain. Mastering them is crucial for creating efficient, data-driven applications in today’s development world.</p><p><strong>JPA (Java Persistence API)</strong></p><p>💎 JPA provides a standard for ORM (Object-Relational Mapping), which allows developers to map Java objects to database tables and perform CRUD (Create, Read, Update, Delete) operations without directly writing SQL.</p><p>💎 JPA itself does not have its own query language. Instead, it uses JPQL (Java Persistence Query Language), which is a query language similar to SQL but operates on entities (Java objects) rather than database tables directly. JPQL is object-oriented and allows developers to query and manipulate data using the JPA-managed entities.</p><p><strong>Hibernate</strong></p><p>💎 Hibernate is a popular ORM framework that implements the JPA specification. It simplifies database interactions by automatically generating SQL queries based on object states, managing transactions, and handling relationships (such as one-to-many and many-to-one).</p><p>💎 Hibernate also offers additional features beyond the JPA standard, such as caching and more advanced query capabilities through Hibernate Query Language (HQL).</p><p>💎 In Hibernate, Java methods and annotations are used to perform CRUD operations (Create, Read, Update, Delete). For example, annotations like @Entity, @Id, @GeneratedValue, etc., define how Java objects map to database tables and handle persistence.</p><p>💎 Hibernate caching techniques (such as First-level cache and Second-level cache) are indeed used to minimize database queries. This improves performance by reducing the number of times data needs to be fetched from the database, thus optimizing resource usage.</p><h3><strong>The main difference between JPA and Hibernate</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*N9Q3ps6O2x7Jc4xqJSPn8Q.png" /><figcaption><strong>comparison table between JPA and Hibernate</strong></figcaption></figure><h3>Conclusion</h3><p>When it comes to Java database management, both JPA and Hibernate offer powerful tools for handling persistence, but understanding their differences is key to making the right choice. <strong>JPA</strong> provides a standardized, lightweight API that allows you to switch between implementations if needed, making it an ideal choice if you value flexibility and interoperability. On the other hand, <strong>Hibernate</strong>, as a robust implementation of JPA, offers additional features like caching, lazy loading, and custom SQL that go beyond the JPA specification, giving you more control over complex database interactions.</p><p><strong>Thank you for reading, and I hope this helps you make the right choice for your project. Have a great day!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8aa28d502b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Spring Boot: A Deep Dive into Architecture and Essential Annotations]]></title>
            <link>https://medium.com/@sudarakakalindu20/mastering-spring-boot-a-deep-dive-into-architecture-and-essential-annotations-f9d1066be564?source=rss-9fbc2d3b538e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9d1066be564</guid>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[annotations]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[folder-structure]]></category>
            <dc:creator><![CDATA[Kalindu Sudaraka]]></dc:creator>
            <pubDate>Wed, 02 Oct 2024 13:45:33 GMT</pubDate>
            <atom:updated>2024-10-02T13:45:33.815Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Sb4A4d6ikQIiA5Hw5YQNA.png" /><figcaption>Get by Canva</figcaption></figure><p>Introduction</p><p>In the world of modern Java development, <strong>Spring Boot</strong> has become the go-to framework for building powerful, production-ready applications with minimal effort. But what makes Spring Boot so popular? It’s not just about writing less boilerplate code, but also about how it organizes your code in a clean and scalable <strong>architecture</strong> while providing a wide range of <strong>annotations</strong> that simplify complex tasks.</p><p>Spring Boot’s layered architecture helps developers write modular code by separating concerns like request handling, business logic, and data persistence into distinct layers. Coupled with its intuitive and flexible annotations, Spring Boot allows you to build applications quickly without compromising on structure or maintainability.</p><p>In this blog post, I’ll dive into the essentials of Spring Boot’s architecture and explore the key annotations that make this framework so developer-friendly. Whether you’re new to Spring or looking to deepen your understanding, this guide will give you a solid foundation to harness the full power of Spring Boot. Let’s get started!</p><p>This is an explanation of the typical layered architecture in Spring Boot, involving Controller, Service, DTO, Repository and Modelpackages. Let&#39;s break down each one,</p><h3><strong>Controller Package:</strong></h3><p>This handles the incoming HTTP requests and sends response to the client, this layer is responsible for processing incoming requests, calling service methods, and returning a response.</p><p>EX: When a user requests to view a list of items, the request is directed to the controller, which is responsible for handling it. The controller interacts with the appropriate services to fetch the necessary data, and then returns the result, typically in JSON format (though it may also return XML, depending on requirements).</p><p><strong>Key annotations:</strong></p><p>@RestController- Marks a class as a REST API controller that handles the HTTP requests (like Get, Post, Delete, and Put)</p><p>@RequestMapping- This is used to map specific URLs to controller methods.(@GetMapping,@PutMapping,@DeleteMapping,@PostMapping)</p><p>Why it’s important: The controller acts as the entry point for the client’s requests, handling routing and request-response cycles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dYGx3pQ_zAj9-6YNg3yBMQ.png" /><figcaption>EmployeeController java class in the Controller package</figcaption></figure><h3><strong>Service Package</strong></h3><p>The service layer contains business logic. It acts as a bridge between the controller and the data access layer (repository). The Service layer should be free from any database or UI concerns.</p><p><strong>Key annotations:</strong></p><p>@Service- Identify the service layer when performing business logic or service-layer operations</p><p>@Transactional- manages <strong>database transactions</strong> automatically without needing to write explicit transaction management code.</p><p>Why it’s important: The service layer encapsulates business logic and promotes separation of concerns, keeping your codebase organized and testable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-roHPfUzC7RktB-Ic0RsKw.png" /><figcaption>EmployeeService java class in the Service package</figcaption></figure><h3><strong>DTO (Data Transfer Object) Package</strong></h3><p>DTO (Data Transfer Object) is used to transfer data between layers (usually from service to controller). DTOs are used to limit the exposure of entity objects or to manipulate data format.</p><p>The DTO typically doesn’t contain any business logic or database annotations. It receives data from the service layer and sends it to the client in a structured format.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U_TQ6AD1lqrsYV6Ll84q-Q.png" /><figcaption>EmployeeDTO java class</figcaption></figure><h3><strong>Repository Package</strong></h3><p>The repository layer interacts with the database. It performs CRUD (Create, Read, Update, Delete) operations by using Spring Data JPA or other database access technologies.</p><p>It uses Spring Data JPA, so you typically define an interface that extends JpaRepository or CrudRepository (Provides built-in methods for performing database operations). Spring Boot generates the necessary code for database operations.</p><p><strong>Key annotation:</strong></p><p>@Repository: Marks a class as a repository that interacts with the database.</p><p>This layer abstracts all data access operations, keeping the service layer free from database-specific code. It allows for flexibility in switching databases or changing the database access logic without affecting other layers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V9mg5NsO4fo7pzLVpbObaA.png" /><figcaption>EmployeeRepository java interface</figcaption></figure><h3><strong>Model (Entity) Package</strong></h3><p>This package contains the Entity classes, which represent database tables. Each class in this package is typically annotated with @Entity and maps to a database table.</p><h4><strong>Key annotations:</strong></h4><p>@Entity: Marks a class as a database entity.</p><p>@Table, @Column, @Id: Used to define the table name, column properties, and primary keys.</p><p>The Model or Entity layer defines the structure of your database and ensures the service and repository layers have a proper data model to work with.</p><p><strong>How data flow in this architecture</strong></p><p>In a typical Spring Boot layered architecture, the data flows through various layers in a well-defined sequence. Let’s walk through the flow of data from the client to the database and back,</p><p>· <strong>Client Request</strong>: GET /api/users/1</p><p>· <strong>Controller</strong>: Handles the request, passes it to the service layer.</p><p>· <strong>Service</strong>: Executes business logic, interacts with the repository.</p><p>· <strong>Repository</strong>: Fetches user data from the database.</p><p>· <strong>Database</strong>: Executes SELECT * FROM users WHERE id = 1;</p><p>· <strong>Repository</strong>: Returns the user data (User entity) to the service.</p><p>· <strong>Service</strong>: Converts the User entity into a UserDTO.</p><p>· <strong>Controller</strong>: Sends the UserDTO as JSON in the HTTP response.</p><p>· <strong>Client</strong>: Receives the JSON response: {“id”: 1, “name”: “Kalindu”, “email”: “kalindu@gmail.com”}.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v_TfvRaIDyziJz5PxmJdLw.png" /></figure><p>Another basic annotation used in the spring boot,</p><p>1. @SpringBootApplication</p><ul><li><strong>Purpose</strong>: This is a combination of three annotations (@Configuration, @EnableAutoConfiguration, @ComponentScan) and marks the main class of a Spring Boot application.</li><li><strong>Why it’s used</strong>: It enables automatic configuration, and component scanning, and bootstraps the application with a single annotation.</li></ul><p>2. @Autowired</p><p>· <strong>Purpose</strong>: Used for automatic dependency injection.</p><p>· <strong>Why it’s used</strong>: It allows Spring to automatically inject beans (like services or repositories) into other classes.</p><p>3. @EnableAutoConfiguration</p><ul><li><strong>Purpose</strong>: Enables Spring Boot’s auto-configuration feature.</li><li><strong>Why it’s used</strong>: It automatically configures beans based on the project’s classpath, making setup easier and reducing boilerplate.</li></ul><h3>Conclusion:</h3><p>That’s a wrap for today! 🎉 I hope this deep dive into <strong>Spring Boot Architecture &amp; Annotations</strong> gave you some valuable insights to level up your development game. Stay tuned — I’ll be back soon with more exciting content to help you master the world of Spring Boot and beyond. Until then, happy coding! 👋🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9d1066be564" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring vs Spring Boot: Understanding the Key Differences]]></title>
            <link>https://medium.com/@sudarakakalindu20/spring-vs-spring-boot-understanding-the-key-differences-1f587692f558?source=rss-9fbc2d3b538e------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f587692f558</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[key-differences]]></category>
            <category><![CDATA[framework]]></category>
            <dc:creator><![CDATA[Kalindu Sudaraka]]></dc:creator>
            <pubDate>Fri, 27 Sep 2024 06:20:20 GMT</pubDate>
            <atom:updated>2024-09-27T06:37:37.727Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nH3T3XjGg9QuwUsQ5xsv5Q.png" /></figure><h3>Spring Framework</h3><p>Spring is an open-source lightweight framework for building Java applications, especially enterprise-level applications (Large-scale software systems).</p><p>It provides various tools and modules to address common programming problems like dependency injection, data access, web services, and security.</p><p>Most of the configurations are done manually, and developers manually define dependencies for Spring projects in the “pom.xml”. Therefore, it is difficult to start a new project.</p><p>In the initial phase of a Spring project, the database and views need to be manually configured, including setting up aspects like database connections and view templates.</p><p>It does not include an embedded web server; therefore, we need to use an external Tomcat server as the web server.</p><h3>Spring Boot Framework</h3><p>Spring Boot is an extension of the Spring Framework; therefore, it encompasses all the features of Spring while enhancing them for easier configuration and development.</p><p>Spring Boot was introduced to reduce boilerplate code and configurations, simplifying the process of creating Spring applications and enabling developers to focus more on business logic.</p><p>Spring Boot Framework is widely used to develop<strong> </strong>REST APIs<strong>.</strong></p><p>Spring Boot’s auto-configuration method automatically configures your Spring application, thereby eliminating the need for manual configuration.</p><p>Basic configurations of Spring Boot can be done using the<strong> </strong><a href="https://start.spring.io/"><strong>Spring Initializr</strong></a> web page, where users can specify the Java version, dependency manager, application version, and initial dependencies.</p><p>In this, dependency managers like Maven and Gradle are introduced to manage dependencies; therefore, the initial setup is simple and fast.</p><p>Spring Boot offers embedded servers such as Jetty and Tomcat, which accelerate the development and testing processes compared to traditional Spring applications.</p><p>Spring Boot is most useful for creating production-ready applications because it simplifies the setup process, provides built in features for monitoring and management, and enables rapid development with minimal configuration.</p><h3>Conclusion</h3><p>Spring and Spring Boot are both powerful frameworks for Java development, but Spring Boot stands out for its rapid setup and ease of use, especially with its embedded servers and auto-configuration features. While Spring requires more manual configuration, Spring Boot streamlines the process, making it ideal for modern, production-ready applications. Both frameworks receive regular updates, but Spring Boot’s updates often introduce new tools and features faster, helping developers stay current with evolving tech trends. For most projects, especially those requiring fast deployment, Spring Boot is the more efficient choice.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5weTygWA2pVQRn3OtIKL5g.png" /></figure><p>Thank you for taking the time to read this blog, I hope it provided valuable insights into Spring and Spring Boot, and I look forward to your feedback and continued engagement!</p><p><strong>Good Luck!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f587692f558" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Monolithic and Microservices Architectures: A Developer’s Perspective]]></title>
            <link>https://medium.com/@sudarakakalindu20/exploring-monolithic-and-microservices-architectures-a-developers-perspective-e6a25fa5d8b8?source=rss-9fbc2d3b538e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6a25fa5d8b8</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[microservice-architecture]]></category>
            <category><![CDATA[monolithicvsmicroservice]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[monolithic-architecture]]></category>
            <dc:creator><![CDATA[Kalindu Sudaraka]]></dc:creator>
            <pubDate>Thu, 26 Sep 2024 04:12:12 GMT</pubDate>
            <atom:updated>2024-09-26T04:12:12.101Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4f_qwNjZQhLBjhkD3HfsZQ.png" /></figure><h3>Monolithic Architecture</h3><p>A traditional model of a software program.</p><p>All the components of an application (Interface, business logic, Database) are built as a single, unified unit.</p><p>All the components are tightly coupled and run as one big code base, making it initially easier to develop and deploy.</p><p>However, as the application grows, it can become harder to manage, update, and scale, since even small changes require redeploying the entire application. That is the disadvantage part of this architecture</p><p>This architecture is used in simple applications, Startups and Early-Stage Projects<strong>,</strong> Tightly Coupled Systems<strong>,</strong> Legacy Systems, Intranet or Enterprise Applications,</p><p>Monolithic architecture can be compared to a large building where all activities and operations occur under one roof. While this structure allows for centralized management and efficiency in small-scale environments, any issue in one part of the system can affect the entire operation, requiring the whole system to be addressed to resolve even a localized problem. This interconnectedness can lead to challenges in scaling, updating, or maintaining the application as it grows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BBHiIDtP6V699KHg5_tLWA.jpeg" /></figure><h3>Microservices Architecture</h3><p>Microservice architecture is a modern software design.</p><p>A collection of small independent services that communicate with each other.</p><p>Each service focuses on a specific functionality (like user management, payments, or notifications) and can operate, be deployed, and scaled independently of others.</p><p>These services communicate with each other through APIs.</p><p>In a microservices architecture, it’s possible to implement different components of a project using multiple programming languages. For instance, an e-commerce platform could be built with Java for core functionalities, while the payment service could be implemented in Python if it’s more suitable for that task. This architecture allows each service to be developed independently, leveraging the strengths of various languages to optimize performance and flexibility across the system.</p><p>Everything is combined into one unit, microservices allow developers to update or scale individual parts of the application without affecting the whole system.</p><p>This makes it more flexible and easier to maintain, especially for large and complex applications.</p><p>This architecture is used in Large and Complex Applications, Highly Scalable Systems, Agile Development Environments, and Cloud-Native Applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0K7tSOKWxo3LpKCHzq51Cw.png" /></figure><h3>Monolithic VS Microservices</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LbML-hLuNAfcOg6jLLdHZQ.png" /></figure><p>Thank you for taking the time to read this article. I hope it provided valuable insights into monolithic and microservices architectures.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6a25fa5d8b8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Singleton Matters: Building Efficient, Scalable Applications]]></title>
            <link>https://medium.com/@sudarakakalindu20/singleton-design-pattern-daf4be272282?source=rss-9fbc2d3b538e------2</link>
            <guid isPermaLink="false">https://medium.com/p/daf4be272282</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[java8]]></category>
            <category><![CDATA[creational-design-pattern]]></category>
            <category><![CDATA[problem-solving]]></category>
            <category><![CDATA[singleton-design-pattern]]></category>
            <dc:creator><![CDATA[Kalindu Sudaraka]]></dc:creator>
            <pubDate>Tue, 16 Jul 2024 16:39:53 GMT</pubDate>
            <atom:updated>2024-10-25T04:11:35.581Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OZiI4gaFaN5-7jrx567Fag.png" /></figure><p>The singleton design pattern is a creational design pattern. Creational design patterns deal with object creation mechanisms, trying to create objects in a manner suitable to the situation.</p><h4><strong>There are 2 methods to implement this design pattern</strong></h4><p><strong>💎 Early initialization</strong>- Early initialization in the Singleton design pattern refers to creating the single instance of the Singleton class at the time of class loading, rather than waiting until it is first needed.</p><p>· Benefits:</p><p>Easy to implement and understand</p><p>· Drawbacks:</p><p>If the singleton instance is never used, the resources allocated for it are wasted</p><p><strong>💎 Lazy initialization</strong>- Lazy initialization in the Singleton design pattern refers to creating the single instance of the Singleton class only when it is first needed, rather than at the time of class loading. After making the object it wants to maintain. Generally, use this method</p><p>· Benefits:</p><p>The Singleton instance is created only if and when it is needed, which can save resources.</p><p>· Drawbacks:</p><p>Adding thread safety can make the implementation more complex.</p><h4><strong>There are 3 steps to implement this singleton design pattern</strong></h4><p>· Private Constructor: The constructor of the class is made private to prevent other classes from creating new instances.</p><p>· Static Variable: A static variable holds the single instance of the class.</p><p>· Public Static Method: A public static method, usually named ‘getInstance()’, provides access to the instance. This method checks if the instance already exists; if not, it creates and returns the instance. If it does, it simply returns the existing instance.</p><p><strong>Implementation</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*Uv_IDRvTPdyJYhpHIDY5rw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*0uZxVXsXZwv7G5moXl--4g.png" /></figure><p><strong>Summary</strong></p><p>The Singleton design pattern ensures a class has only one instance and provides a global access point to it, making it a popular creational design pattern. It restricts instantiation to a single object, saving resources and ensuring consistent behavior across an application. Implementation can be through early initialization, where the instance is created at class loading, or lazy initialization, where it is created when first needed. While Singleton offers controlled access and reduced memory usage, it can introduce global state and complicate unit testing. Thread-safety must be considered, especially in lazy initialization.</p><h4>Happy coding! See you soon with another powerful design pattern to elevate your projects.</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=daf4be272282" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Patterns: Writing Reusable, Maintainable, and Flexible Code]]></title>
            <link>https://medium.com/@sudarakakalindu20/software-design-patterns-3e314b98c28e?source=rss-9fbc2d3b538e------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e314b98c28e</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[creational-design-pattern]]></category>
            <category><![CDATA[structural-design-pattern]]></category>
            <category><![CDATA[software-design-patterns]]></category>
            <category><![CDATA[behavioral-design-pattern]]></category>
            <dc:creator><![CDATA[Kalindu Sudaraka]]></dc:creator>
            <pubDate>Tue, 11 Jun 2024 17:42:55 GMT</pubDate>
            <atom:updated>2024-10-18T03:45:30.814Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ghjB2i2xtRxEc1ET_IlqFg.png" /></figure><h3><strong>What is?</strong></h3><p>· Design patterns represent a thought process that involves abstract thinking about how to solve a problem.</p><p>· They can be applied to different processes and problems across various contexts in software development.</p><p>· Design patterns provide a framework for solving recurring design problems by defining a clear, standardized approach.</p><h3><strong>Why do we use it?</strong></h3><p>· can speed up the development process.</p><p>· Design patterns provide reusable solutions that can be applied to similar problems across different projects, saving time and effort.</p><p>· can improve our code capacity.</p><p>· Using a common set of patterns improves communication among developers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*eRD4P_amRlTKT13POP1olQ.png" /></figure><h3><strong>Types of Design Patterns</strong></h3><h4>Creational Patterns</h4><p>Creational patterns deal with object creation mechanisms, aiming to create objects in a manner suitable to the situation.</p><ol><li>Factory Pattern</li><li>Abstract Factory Pattern</li><li>Singleton Pattern</li><li>Prototype Pattern</li><li>Builder Pattern.</li></ol><p>Benefits:</p><p>· Improve the design by controlling the object creation process.</p><p>· Provide more flexibility and decoupling in code.</p><h4><strong>Structural Patterns</strong></h4><p>Structural patterns deal with object composition and typically help ensure that if one part of a system changes, the entire system doesn’t need to.</p><ol><li>Adapter Pattern</li><li>Bridge Pattern</li><li>Composite Pattern</li><li>Decorator Pattern</li><li>Facade Pattern</li><li>Flyweight Pattern</li><li>Proxy Pattern</li></ol><p>Benefits:</p><p>· Simplify complex object structures.</p><p>· Improve system scalability and flexibility.</p><h4><strong>Behavioral Patterns</strong></h4><p>Behavioral patterns deal with object interaction and responsibility distribution, focusing on how objects communicate and how responsibilities are distributed among them.</p><ol><li>Chain-of-Responsibility Pattern</li><li>Command Pattern</li><li>Interpreter Pattern</li><li>Iterator Pattern</li><li>Mediator Pattern</li><li>Memento Pattern</li><li>Observer Pattern</li><li>State Pattern</li><li>Strategy Pattern</li><li>Template Pattern</li><li>Visitor Pattern</li></ol><p>Benefits:</p><p>· Enhance flexibility and communication between objects.</p><p>· Improve code maintainability and scalability by promoting loose coupling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*1mnwZQnFsNTNew6L8lZeZg.jpeg" /></figure><h4>Summary</h4><p>Software design patterns are established solutions to common problems encountered in software design. They serve as templates to guide the development of flexible, reusable, and maintainable code.</p><h4>Good Luck!</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e314b98c28e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking the Power of React: A Complete Guide to All Hooks]]></title>
            <link>https://medium.com/@sudarakakalindu20/all-react-hooks-in-one-49d5993ed779?source=rss-9fbc2d3b538e------2</link>
            <guid isPermaLink="false">https://medium.com/p/49d5993ed779</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[hooks]]></category>
            <category><![CDATA[functional-component]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Kalindu Sudaraka]]></dc:creator>
            <pubDate>Wed, 05 Jun 2024 21:55:38 GMT</pubDate>
            <atom:updated>2024-10-18T09:57:32.447Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-vuuV-nPYUFSyfaSwEnGEQ.png" /></figure><h3><strong>Introduction</strong></h3><p>React Hooks are special functions that allow you to use state and other React features in functional components. Hooks are reusable functions. They let you “hook into” React’s state and lifecycle features without writing class components. Hooks were added to React in version 16.8. In this blog, we’ll dive into some of the most frequently used React hooks and provide clear, easy-to-understand examples to help you get started.</p><h3>useState hook</h3><p>The ‘useState’ Hook is a function that lets you add state to functional components in React. It allows you to create state variables that can hold values and be updated as needed.</p><p>The primary purpose of the ‘useState’ Hook is to enable state management in functional components.</p><p><strong>Use the ‘useState’ hook when you need to:</strong></p><p>· Keep track of values that may change over time (e.g., user inputs, form data, toggles)</p><p>· Respond to user interactions (e.g., button clicks, input changes).</p><p>· Manage simple stateful logic without the overhead of class components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g9b3uOBaMeRQb-23MOgPmw.png" /></figure><h3><strong>UseEffect hook</strong></h3><p>The useEffect Hook is a function in React that allows you to perform side effects in your functional components. Side effects are operations that affect something outside the scope of the function being executed, like fetching data, updating the DOM, or setting up subscriptions.</p><p><strong>Purpose of useEffect</strong></p><p>· Data Fetching: Retrieve data from an API and update the component state with the fetched data.</p><p>· DOM Manipulation: Perform operations that affect the DOM, such as updating the document title or interacting with third-party libraries.</p><p>· Subscriptions: Set up subscriptions or timers and clean them up when the component unmounts.</p><p>Use ‘useEffect’ whenever you need to perform an action that goes beyond rendering the component, such as:</p><p>· Fetching data from an external source.</p><p>· Directly interacting with the DOM.</p><p>· Setting up a timer or subscription that needs to be cleaned up later.</p><p>Use ‘useEffect’ inside your functional component. It takes two arguments, a function and a dependency array.</p><p>Function: This function contains the side effect code you want to run.</p><p>Dependency Array: This array determines when the side effect should be re-run. If empty, the effect runs only once after the initial render.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*coNWqFsHhkBbDQ4LKuNRWg.png" /></figure><h3><strong>useContext hook</strong></h3><p>The ‘useContext’ Hook is a React function that allows you to access and share data across your component tree without having to pass props down manually at every level. It simplifies the management of global state in a React application.</p><p><strong>Purpose of ‘useContext’</strong></p><p>· State Management: It helps manage and share state or data across multiple components in a React application.</p><p>· Avoid Prop Drilling: It eliminates the need for “prop drilling,” which is passing data through many nested components.</p><p>· Simplify Code: Makes the code cleaner and easier to maintain by centralizing state management.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*GSK2WYHaGJd4LDRvnXNT_Q.png" /></figure><h3><strong>useRef hook</strong></h3><p>The ‘useRef’ hook is a powerful tool in React that allows you to create a reference to a DOM element or persist values across renders without causing a re-render.</p><p><strong>Purpose of ‘useRef’</strong></p><p>· Access DOM Elements: ‘useRef’ is commonly used to directly access and interact with a DOM element.</p><p>· Persist Values: It can also be used to persist values across renders without triggering a re-render. This is useful for storing mutable values that don’t need to cause the component to re-render when changed</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*iDoYptPMlfow-fX8rrK2bg.png" /></figure><h3><strong>useReducer hook</strong></h3><p>The ‘useReducer’ Hook is used for managing more complex state logic in React functional components. It’s an alternative to ‘useState’ that is better suited for situations where the state has multiple sub-values or when the next state depends on the previous one.</p><p><strong>When is it used?</strong></p><p>· Complex State Logic: When you have a component with state logic that involves multiple sub-values or complex transitions.</p><p>· State Dependent on Previous State: When the new state is based on changes to the previous state, making ‘useReducer’ more predictable and easier to manage.</p><p>· Multiple Actions: When you need to handle multiple state transitions (actions) in a structured way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/1*xR30Tty-a3_VpG6LhDOQNQ.png" /></figure><h3><strong>useCallback hook</strong></h3><p>The useCallback Hook is a function that returns a memoized version of a callback function. This helps to optimize performance by preventing unnecessary re-creations of the callback function.</p><p><strong>Purpose of ‘useCallback’</strong></p><p>· Performance Optimization: useCallback is used to memoize functions so that they are not recreated on every render, which can be useful when passing functions as props to child components. This helps to prevent unnecessary re-renders of child components.</p><p>The ‘useCallback’ and ‘useMemo’ Hooks are similar. The main difference is that ‘useMemo’ returns a memoized value and ‘useCallback’ returns a memoized function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*6vaXfubiQP0Xta_3c8d4hg.png" /></figure><h3><strong>useMemo hook</strong></h3><p>The React useMemo Hook returns a memoized value.</p><p><strong>What is the Purpose?</strong></p><p>· The ‘useMemo’ hook is used to optimize performance by memoizing the result of a calculation or function. This means it only recomputes the memoized value when one of its dependencies has changed, preventing unnecessary recalculations on every render.</p><p>The ‘useMemo’ hook can be used to keep expensive, resource intensive functions from needlessly running.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*M8ZYrm-6OrRC31WQfZ6VJA.png" /></figure><h3><strong>Custom hook</strong></h3><p>A custom hook is a function in React that allows you to encapsulate and reuse stateful logic across multiple components. It’s essentially a way to extract logic that uses React hooks and make it shareable.</p><p><strong>Purpose of Custom Hooks</strong></p><p>· Reuse Logic: Custom hooks let you reuse stateful logic without duplicating code. This makes your code more modular and maintainable.</p><p>· Organize Code: They help organize your code better by separating the concerns of your application.</p><p><strong>When to Use Custom Hooks</strong></p><p>· Repeated Logic: When you find yourself writing the same logic in multiple components, you can create a custom hook to encapsulate this logic.</p><p>· Complex Logic: For complex logic that deals with state or side effects, a custom hook can help to keep your component code cleaner and more focused on rendering.</p><p><strong>How to Create and Use a Custom Hook</strong></p><p>· Define the Custom Hook: A custom hook is a JavaScript function whose name starts with use, and it can call other hooks inside it.</p><p>· Use the Custom Hook: You can use the custom hook inside any functional component just like you would use React’s built-in hooks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*bqmtIVBfLOVUAHK9CEgyDA.png" /></figure><h3><strong>Summary</strong></h3><p>React Hooks are special functions that allow you to use state and other React features in functional components. Introduced in React 16.8, hooks enable you to write cleaner, more efficient, and more modular code without the need for class components.</p><p><strong>Key Features of React Hooks:</strong></p><p>1. useState: Adds state to functional components.</p><p>2. useEffect: Manages side effects such as data fetching and subscriptions.</p><p>3. useContext: Accesses context values without needing to pass props down manually.</p><p>4. useReducer: Manages more complex state logic, similar to Redux.</p><p>5. useRef: Accesses DOM elements or stores mutable values across renders.</p><p>6. useMemo: Optimizes performance by memoizing expensive calculations.</p><p>7. useCallback: Memoizes functions to avoid unnecessary re-creation of functions on re-renders.</p><p>Custom Hooks:</p><p>Purpose: Custom hooks allow you to encapsulate and reuse stateful logic across multiple components.</p><p>Usage: They are created as JavaScript functions starting with `use` and can call other hooks inside them.</p><p>Benefits: Enhance code reusability and maintainability by extracting and sharing common logic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/1*7c0UH5ycWTEp4aIuWnkIxw.jpeg" /></figure><h4>If you like it then don’t forget to like and follow. Good Luck!</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49d5993ed779" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Lifecycle]]></title>
            <link>https://medium.com/@sudarakakalindu20/react-lifecycle-d072644a30af?source=rss-9fbc2d3b538e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d072644a30af</guid>
            <category><![CDATA[mounting]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-lifecycle]]></category>
            <category><![CDATA[unmounting]]></category>
            <category><![CDATA[updating]]></category>
            <dc:creator><![CDATA[Kalindu Sudaraka]]></dc:creator>
            <pubDate>Thu, 30 May 2024 18:46:01 GMT</pubDate>
            <atom:updated>2024-05-30T18:46:01.966Z</atom:updated>
            <content:encoded><![CDATA[<h3>Lifecycle of Components</h3><p>In react, components have a life cycle that consists of different phases. Each phase has a set lifecycle method, React lifecycle methods are special methods in a React component that allow you to run code at specific points in a component’s life. These methods are part of class components and enable you to manage a component’s behavior during its existence in your application. In functional components, hooks are used to perform tasks that would traditionally be handled by lifecycle methods in class components.</p><p>The lifecycle of a React component consists of three main phases: mounting, updating, and unmounting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*IdOFIB5jmXgs2AllYtOLaA.jpeg" /><figcaption><a href="https://medium.com/@habilelabs?source=post_page-----5269aaa37046--------------------------------">HabileLabs</a></figcaption></figure><h3><strong>Mounting</strong></h3><p>The Mounting phase begins when a component is first created and placed into the DOM.</p><p>React calls these four built-in methods, in this order, when mounting a component</p><ol><li>constructor()</li><li>getDerivedStateFromProps()</li><li>render()</li><li>componentDidMount()</li></ol><p><strong>Constructor ()</strong></p><p>Purpose: This method is called when the component is being created and initialized.</p><p>Usage: It’s typically used to initialize state and bind methods.</p><p>The constructor() method is called with the props as argument</p><p><strong>getDerivedStateFromProps()</strong></p><p>Purpose: This method is called right before rendering the component, both during the initial mount and subsequent updates.</p><p>Usage: It’s used to update the state based on changes in props. It’s a static method, meaning it doesn’t have access to ‘this’.</p><p><strong>render()</strong></p><p>Purpose: This method is required and is responsible for describing what the UI should look like.</p><p>Usage: It returns the React elements (JSX) that make up the component’s UI.</p><p><strong>componentDidMount()</strong></p><p>Purpose: This method is called after the component has been rendered to the DOM.</p><p>Usage: It’s commonly used for making API calls, setting up subscriptions, or any other side effects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/279/1*xDS7r2f7PcU1dFS24K7xpw.png" /></figure><h3><strong>Updating</strong></h3><p>The Updating phase occurs whenever there is a change in the component’s data, either from its own state or from its properties (props) provided by its parent component.</p><p>React has five built-in methods that gets called, in this order, when a component is updated:</p><ol><li>getDerivedStateFromProps()</li><li>shouldComponentUpdate()</li><li>render()</li><li>getSnapshotBeforeUpdate()</li><li>componentDidUpdate()</li></ol><p><strong>getDerivedStateFromProps()</strong></p><p>Called During Updates: ‘getDerivedStateFromProps’ is the first method called when a component updates.</p><p>Updates State Based on Props: This method is the natural place to update the state object based on changes in props.</p><p><strong>shouldComponentUpdate()</strong></p><p>In the `shouldComponentUpdate()` method, you can return a Boolean value to specify whether React should continue with the rendering process or not. By default, it returns `true`,</p><p>meaning React will re-render the component whenever there are changes in props or state. If you return `false`, React will skip the rendering and updating process for that update cycle. This can be useful for optimizing performance by preventing unnecessary renders.</p><p><strong>Render()</strong></p><p>The ‘render()’ method is called when a component gets updated. It is responsible for re-rendering the HTML to the DOM to reflect the new changes.</p><p><strong>getSnapshotBeforeUpdate()</strong></p><p>The `getSnapshotBeforeUpdate()` method lets you capture the props and state before an update, which can be useful for tasks like recording the scroll position.</p><p>If you use `getSnapshotBeforeUpdate()`, you must also implement `componentDidUpdate()`, as it receives the value returned by `getSnapshotBeforeUpdate()`. Without `componentDidUpdate()`, you will get an error. This pairing ensures that any pre-update information can be properly used after the update.</p><p><strong>componentDidUpdate()</strong></p><p>The componentDidUpdate method is called after the component is updated in the DOM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*TfU31mhZUJNae8HABaAoTw.jpeg" /><figcaption>GeeksforGeeks</figcaption></figure><h3><strong>Unmounting</strong></h3><p>The unmounting phase occurs when a component is removed from the DOM.</p><p>React has only one built-in method that gets called when a component is unmounted:</p><p><strong>componentWillUnmount()</strong></p><p>The<strong> componentWillUnmount() </strong>method is called when the component is about to be removed from the DOM.</p><h3><strong>Summary</strong></h3><p>React lifecycle methods help manage a component’s behavior at different stages of its existence. During mounting, methods like `constructor()`, `getDerivedStateFromProps()`, `render()`, and `componentDidMount()` initialize the component and handle side effects. In the updating phase, `getDerivedStateFromProps()`, `shouldComponentUpdate()`, `render()`, `getSnapshotBeforeUpdate()`, and `componentDidUpdate()` manage state changes and optimize re-renders. Finally, `componentWillUnmount()` handles cleanup before the component is removed from the DOM. These methods ensure efficient and effective component management throughout its lifecycle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H-Iw5Sro6riyB1fMD1qrXw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d072644a30af" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>