<?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 Joginder Kumar on Medium]]></title>
        <description><![CDATA[Stories by Joginder Kumar on Medium]]></description>
        <link>https://medium.com/@joginder.kumar1991?source=rss-e011bad5ed66------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*fzlaLaPxgG1g9NkA.jpg</url>
            <title>Stories by Joginder Kumar on Medium</title>
            <link>https://medium.com/@joginder.kumar1991?source=rss-e011bad5ed66------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 13:55:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@joginder.kumar1991/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[Understanding and Implementing the State Design Pattern in Java]]></title>
            <link>https://medium.com/@joginder.kumar1991/understanding-and-implementing-the-state-design-pattern-in-java-fbec9b6356c3?source=rss-e011bad5ed66------2</link>
            <guid isPermaLink="false">https://medium.com/p/fbec9b6356c3</guid>
            <category><![CDATA[state-design-pattern]]></category>
            <category><![CDATA[behavioural-design]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Joginder Kumar]]></dc:creator>
            <pubDate>Tue, 30 Apr 2024 09:33:31 GMT</pubDate>
            <atom:updated>2024-04-30T09:33:31.936Z</atom:updated>
            <content:encoded><![CDATA[<p>In the world of software design patterns, the State pattern stands out as a powerful tool for managing the behavior of objects in various states. It allows objects to alter their behavior when their internal state changes, without changing their class.</p><p>In this article, we’ll explore the State design pattern in Java by implementing it in a real-world scenario: a vending machine system. We’ll walk through the code implementation and discuss its benefits and use cases.</p><h3>What is the State Design Pattern?</h3><p>The State pattern is a behavioral design pattern that allows an object to change its behavior when its internal state changes. It encapsulates state-specific behavior into separate classes and delegates the responsibility of state transitions to these classes.</p><p>At its core, the State pattern consists of the following components:</p><ul><li>Context: The object whose behavior changes based on its internal state.</li><li>State: An interface or abstract class that defines a set of methods representing state-specific behavior.</li><li>Concrete States: Classes that implement the State interface, each representing a specific state of the Context object.</li></ul><h3>Implementing the State Design Pattern: Vending Machine Example</h3><p>Let’s dive into a practical example to better understand the State pattern. We’ll implement a vending machine system where the vending machine can be in different states based on user interactions.</p><h3>Setting Up the Project</h3><p>You can find the complete source code for this example in <a href="https://github.com/jogiii/all_design_patterns/tree/main/src/main/java/com/design/patterns/behavioural/state_design">this GitHub repository</a>.</p><h3>Class Diagram</h3><p>Before we delve into the implementation details, let’s create a class diagram to visualize the structure of our vending machine system using PlantUML:</p><p>This diagram illustrates the relationships between the VendingMachine class and its various states (IdleState, HasMoneyState, SelectionState, DispenseState).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mMjgdLzaJ3x2k4MIEmJhug.png" /></figure><h3>Understanding the Code</h3><p>Now, let’s dissect the code to understand how the State pattern is implemented in the vending machine system.</p><h4>VendingMachine Class</h4><p>The VendingMachine class represents the context in our system. It maintains a reference to the current state (currentState) and provides methods for interacting with the vending machine, such as insertCoin(), chooseProduct(), getChange(), and refundMoney().</p><pre>public class VendingMachine {<br>    private State currentState;<br>// Other attributes and methods omitted for brevity<br>    public void setState(State state) {<br>        this.currentState = state;<br>    }<br>    public void insertCoin() {<br>        currentState.handleInsertCoin(this);<br>    }<br>    public void chooseProduct() {<br>        currentState.handleChooseProduct(this);<br>    }<br>    public void getChange() {<br>        currentState.handleGetChange(this);<br>    }<br>    public void refundMoney() {<br>        currentState.handleRefundMoney(this);<br>    }<br>}</pre><h4>State Interface and Concrete State Classes</h4><p>The State interface defines a set of methods representing state-specific behavior. Each concrete state class (IdleState, HasMoneyState, SelectionState, DispenseState) implements these methods to handle actions based on the vending machine&#39;s current state.</p><pre>public interface State {<br>    void handleInsertCoin(VendingMachine vendingMachine);<br>    void handleChooseProduct(VendingMachine vendingMachine);<br>    void handleGetChange(VendingMachine vendingMachine);<br>    void handleRefundMoney(VendingMachine vendingMachine);<br>}</pre><pre>public class IdleState implements State {<br>    // Implementation of State methods for IdleState<br>}<br>// Implementations for other concrete state classes (HasMoneyState, SelectionState, DispenseState) omitted for brevity</pre><h3>Real-Life Example: Traffic Light System</h3><p>A real-life example where the State pattern is commonly used is in the implementation of a traffic light system. Each traffic light can be in different states (e.g., red, yellow, green), and its behavior (e.g., allowing traffic flow, stopping vehicles) changes based on its current state.</p><h3>Conclusion</h3><p>The State design pattern is a powerful tool for managing state-dependent behavior in object-oriented systems. By encapsulating state-specific behavior into separate classes, it promotes code maintainability, extensibility, and readability.</p><p>In this article, we explored the implementation of the State pattern in a vending machine system. We discussed its components, dissected the code implementation, and visualized the class diagram using PlantUML. Additionally, we highlighted a real-life example where the State pattern is commonly used.</p><p>Understanding and applying design patterns like the State pattern is essential for building robust and maintainable software systems. By mastering these patterns, developers can design more flexible and scalable solutions to complex problems.</p><p>Thank you for reading! If you found this article helpful, feel free to share it with your peers. Happy coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fbec9b6356c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the Observer Design Pattern with a Real-World Example]]></title>
            <link>https://medium.com/@joginder.kumar1991/understanding-the-observer-design-pattern-with-a-real-world-example-e1e62712eb4c?source=rss-e011bad5ed66------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1e62712eb4c</guid>
            <category><![CDATA[observer-design-pattern]]></category>
            <category><![CDATA[behavioural-design]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Joginder Kumar]]></dc:creator>
            <pubDate>Mon, 29 Apr 2024 18:39:40 GMT</pubDate>
            <atom:updated>2024-04-29T18:45:07.002Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction</strong></p><p>In software development, the Observer Design Pattern is a powerful mechanism for establishing a one-to-many dependency between objects. It enables an object (the subject) to notify other objects (observers) about changes in its state. This notification allows observers to react accordingly, promoting loose coupling and a clean separation of concerns.</p><p><strong>Core Components</strong></p><p>The Observer Pattern involves two primary components:</p><ol><li><strong>Subject (Observable):</strong> The object that maintains state and notifies dependent objects (observers) about changes. It provides interfaces for adding, removing, and notifying observers.</li><li><strong>Observer:</strong> The object that registers with the subject to be notified of state changes. It implements an update() method to receive notifications and take appropriate actions.</li></ol><p><strong>Benefits</strong></p><ul><li><strong>Loose Coupling:</strong> Observers don’t need to know the subject’s concrete implementation. They interact through interfaces, promoting modularity and maintainability.</li><li><strong>Flexibility:</strong> New observers can be added or removed dynamically without modifying the subject’s code.</li><li><strong>Decoupling State Management:</strong> Observers can handle state changes independently, simplifying the subject’s logic.</li></ul><p><strong>Real-World Example: Stock Notification System</strong></p><p>Imagine an e-commerce platform where users want to be notified when a product (e.g., iPhones) comes back in stock. We can leverage the Observer Pattern to implement this functionality:</p><ul><li><strong>Subject:</strong> StocksObservable (interface): Defines methods to add/remove observers, notify them, and set/get stock count.</li><li><strong>Concrete Subject:</strong> IphoneObservableImpl (class): Implements StocksObservable, maintains the stock count, and notifies observers when stock changes.</li><li><strong>Observer:</strong> NotificationAlertObserver (interface): Defines the update() method for observers to react to stock updates.</li><li><strong>Concrete Observers:</strong></li><li>EmailAlertObserverImpl: Sends an email notification (simulated by printing to console).</li><li>MobileAlertObserverImpl: Sends a mobile notification (simulated by printing to console).</li></ul><p><strong>Code Walkthrough</strong></p><p>The provided code demonstrates the Observer Pattern in action:</p><p><strong>Store Class (Main Method):</strong></p><ul><li>Creates an IphoneObservableImpl instance (subject).</li><li>Creates EmailAlertObserverImpl and MobileAlertObserverImpl instances (observers).</li><li>Registers observers with the StocksObservable.</li><li>Sets the stock count to 10, triggering notifications.</li></ul><p><strong>NotificationAlertObserver Interface:</strong></p><ul><li>Declares the update() method for observers to implement.</li></ul><p><strong>EmailAlertObserverImpl:</strong></p><ul><li>Stores the email address and reference to the subject.</li><li>Overrides update() to send email notifications.</li></ul><p><strong>MobileAlertObserverImpl:</strong></p><ul><li>Stores the username and reference to the subject.</li><li>Overrides update() to send mobile notifications.</li></ul><p><strong>StocksObservable Interface:</strong></p><ul><li>Defines methods for adding/removing observers, notifying them, setting/getting stock count.</li></ul><p><strong>IphoneObservableImpl:</strong></p><ul><li>Implements StocksObservable.</li><li>Maintains a list of registered observers and the stock count.</li><li>Implements methods for adding/removing observers, notifying them (iterating through the list and calling update() on each observer), and setting/getting stock count (notifies observers only if stock changes from 0 to a positive value).</li></ul><p><strong>UML Diagram</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8MGU8-Fw1qWZhoPZWDNiqg.png" /><figcaption>UML Diagram</figcaption></figure><p>Code:</p><pre>public class Store {<br><br>    public static void main(String[] args) {<br>        StocksObservable iphoneStocksObservable = new IphoneObservableImpl();<br><br>        NotificationAlertObserver observer1 = new EmailAlertObserverImpl(&quot;xyz@gmail.com&quot;, iphoneStocksObservable);<br>        NotificationAlertObserver observer2 = new EmailAlertObserverImpl(&quot;xyz1@gmail.com&quot;, iphoneStocksObservable);<br>        NotificationAlertObserver observer3 = new MobileAlertObserverImpl(&quot;xyz_username&quot;,iphoneStocksObservable);<br><br>        iphoneStocksObservable.add(observer1);<br>        iphoneStocksObservable.add(observer2);<br>        iphoneStocksObservable.add(observer3);<br><br>        iphoneStocksObservable.setStockCount(10);<br><br>    }<br>}<br><br><br>public interface NotificationAlertObserver {<br><br>    public void update();<br>}<br><br><br>public class MobileAlertObserverImpl implements NotificationAlertObserver{<br><br>    String userName;<br>    StocksObservable observable;<br><br>    public MobileAlertObserverImpl(String username, StocksObservable observable){<br>        this.userName = username;<br>        this.observable = observable;<br>    }<br>    @Override<br>    public void update() {<br><br>        sendMessageOnMobile(userName,&quot;product is in stock hurry up !&quot;);<br><br>    }<br><br>    public void sendMessageOnMobile(String userName, String msg){<br>        System.out.println(&quot;message sent to :&quot;+userName);<br>    }<br>}<br><br>public class EmailAlertObserverImpl implements NotificationAlertObserver{<br><br>    String emailId;<br>    StocksObservable observable;<br><br>    public EmailAlertObserverImpl(String emailId, StocksObservable observable){<br>        this.observable = observable;<br>        this.emailId = emailId;<br>    }<br>    @Override<br>    public void update() {<br>        sendMail(emailId,&quot;product in stock hurry up !!&quot;);<br>    }<br><br>    public void sendMail(String emailId, String msg){<br>        System.out.println(&quot;email sent to: &quot;+emailId);<br>    }<br>}<br><br><br>public interface StocksObservable{<br>    public void add(NotificationAlertObserver observer);<br><br>    public void remove(NotificationAlertObserver observer);<br>    public void notifySubscriber();<br>    public void setStockCount(int newStockAdded);<br><br>    public int getStockCount();<br>}<br><br><br><br>import java.util.ArrayList;<br>import java.util.List;<br><br>public class IphoneObservableImpl  implements StocksObservable{<br>    public List&lt;NotificationAlertObserver&gt; observerList = new ArrayList&lt;&gt;();<br>    public int stockCount = 0;<br><br>    @Override<br>    public void add(NotificationAlertObserver observer) {<br>        observerList.add(observer);<br>    }<br><br>    @Override<br>    public void remove(NotificationAlertObserver observer) {<br>        observerList.remove(observer);<br>    }<br><br>    @Override<br>    public void notifySubscriber() {<br>        for(NotificationAlertObserver observer : observerList){<br>            observer.update();<br>        }<br><br>    }<br><br>    @Override<br>    public void setStockCount(int newStockAdded) {<br><br>        if(stockCount ==0)<br>            notifySubscriber();<br><br>        stockCount = stockCount+ newStockAdded;<br><br>    }<br><br>    @Override<br>    public int getStockCount() {<br>        return stockCount;<br>    }<br>}</pre><p><strong>Real-World Applications</strong></p><p>The Observer Pattern is widely used in various software domains:</p><ul><li><strong>GUI Frameworks:</strong> When a user interacts with a UI control (subject), other UI elements (observers) update accordingly (e.g., button state changes based on checkbox selections).</li><li><strong>News Aggregators:</strong> News feeds (subject) notify subscribed clients (observers) about new articles (updates).</li><li><strong>Task Management Systems:</strong> Task status changes (subject) can trigger notifications for assigned users (observers).</li><li><strong>Server-Sent Events (SSE):</strong> Servers (subject) can push real-time updates to connected clients (observers) without requiring constant polling.</li></ul><p><strong>Conclusion</strong></p><p>The Observer Design Pattern is a valuable tool for creating loosely coupled, dynamic, and maintainable object interactions in Java. It fosters clear separation of concerns and enables consistent state management across dependent objects. By understanding its core principles</p><p>You can find the complete code example on <a href="https://github.com/jogiii/all_design_patterns/tree/main/src/main/java/com/design/patterns/behavioural/observer_design">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1e62712eb4c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Strategy Design Pattern in Java: A Practical Guide]]></title>
            <link>https://medium.com/@joginder.kumar1991/implementing-strategy-design-pattern-in-java-a-practical-guide-d5abd3c3f5e9?source=rss-e011bad5ed66------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5abd3c3f5e9</guid>
            <category><![CDATA[design-pattern-in-java]]></category>
            <category><![CDATA[strategy-design-pattern]]></category>
            <category><![CDATA[creational-design-pattern]]></category>
            <dc:creator><![CDATA[Joginder Kumar]]></dc:creator>
            <pubDate>Mon, 22 Apr 2024 18:34:50 GMT</pubDate>
            <atom:updated>2024-04-22T18:34:50.127Z</atom:updated>
            <content:encoded><![CDATA[<p>Strategy design pattern is a behavioral design pattern that allows an algorithm’s behavior to be selected at runtime. It enables selecting an algorithm’s behavior from a family of algorithms, encapsulates each one, and makes them interchangeable.</p><p>In this article, we will explore the strategy design pattern with a practical example in Java. We’ll delve into the code implementation, understand its benefits, potential problems when not using it, and explore a real-life example.</p><h3>Understanding the Strategy Design Pattern</h3><p>The strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. This pattern lets the algorithm vary independently from clients that use it.</p><h3>Components of the Strategy Design Pattern</h3><ul><li>Strategy: Defines a set of algorithms, encapsulated and interchangeable.</li><li>Concrete Strategy: Implements the algorithm defined in the Strategy interface.</li><li>Context: Maintains a reference to a Strategy object and provides an interface to invoke the algorithm defined in the Strategy.</li></ul><h3>Example: Vehicle and Drive Strategy</h3><p>Let’s consider a scenario where we have different types of vehicles, and each vehicle can have a different driving strategy. We’ll implement the strategy design pattern to encapsulate the driving strategies and make them interchangeable.</p><h3>UML Diagram</h3><p>Here’s a UML diagram representing the strategy design pattern for our example:</p><pre>                +------------------+<br>                |     Vehicle      |<br>                +------------------+<br>                | - driveStrategy  |<br>                +------------------+<br>                         |<br>                         |<br>                         |<br>                +------------------+<br>                |   DriveStrategy  |<br>                +------------------+<br>                | + drive()        |<br>                | + engine()       |<br>                +------------------+<br>                         /      \<br>                        /        \<br>                       /          \<br>         +------------------+   +------------------+<br>         | NormalDriveStrategy|  | SportsDriveStrategy|<br>         +------------------+   +------------------+<br>         | + drive()        |   | + drive()        |<br>         | + engine()       |    | + engine()       |<br>         +------------------+    +------------------+<br>                        <br>              </pre><h3>Code Implementation</h3><pre>// DriveStrategy.java<br>public interface DriveStrategy {<br>    void drive();<br>    void engine();<br>}</pre><pre>// NormalDriveStrategy.java<br>public class NormalDriveStrategy implements DriveStrategy {<br>    @Override<br>    public void drive() {<br>        System.out.println(&quot;Normal drive strategy&quot;);<br>    }</pre><pre>    @Override<br>    public void engine() {<br>        System.out.println(&quot;Normal Engine Strategy&quot;);<br>    }<br>}</pre><pre>// SportsDriveStrategy.java<br>public class SportsDriveStrategy implements DriveStrategy {<br>    @Override<br>    public void drive() {<br>        System.out.println(&quot;Sports drive strategy&quot;);<br>    }</pre><pre>    @Override<br>    public void engine() {<br>        System.out.println(&quot;Sports engine strategy&quot;);<br>    }<br>}</pre><pre>// Vehicle.java<br>public class Vehicle {<br>    DriveStrategy driveStrategy;</pre><pre>    public Vehicle(DriveStrategy driveStrategy) {<br>        this.driveStrategy = driveStrategy;<br>    }</pre><pre>    public void drive() {<br>        driveStrategy.drive();<br>    }</pre><pre>    public void engine() {<br>        driveStrategy.engine();<br>    }<br>}</pre><pre>// Main.java<br>public class Main {<br>    public static void main(String[] args) {<br>        Vehicle vehicle = new SportsVehicle();<br>        vehicle.drive();<br>        vehicle.engine();<br>    }<br>}</pre><pre>// GoodsVehicle.java<br>public class GoodsVehicle extends Vehicle {<br>    public GoodsVehicle() {<br>        super(new SportsDriveStrategy());<br>    }<br>}</pre><pre>// NormalVehicle.java<br>public class NormalVehicle extends Vehicle {<br>    public NormalVehicle() {<br>        super(new NormalDriveStrategy());<br>    }<br>}</pre><pre>// OffRoadVehicle.java<br>public class OffRoadVehicle extends Vehicle {<br>    public OffRoadVehicle() {<br>        super(new SportsDriveStrategy());<br>    }<br>}</pre><pre>// SportsVehicle.java<br>public class SportsVehicle extends Vehicle {<br>    public SportsVehicle() {<br>        super(new SportsDriveStrategy());<br>    }<br>}</pre><h3>Problems Without Using Strategy Design Pattern</h3><ol><li>Code Duplication: Without the strategy pattern, if we want to introduce a new driving strategy, we would need to modify the existing Vehicle class, leading to code duplication and violating the Open/Closed Principle.</li><li>Limited Flexibility: Changing the driving behavior would require modifying the Vehicle class directly, making the system less flexible and harder to maintain.</li><li>Tight Coupling: The driving behavior is tightly coupled with the Vehicle class, making it challenging to change or extend without affecting other parts of the system.</li></ol><h3>Real-life Example</h3><p>Consider an e-commerce platform where customers can choose different payment methods like Credit Card, PayPal, and Bitcoin. Each payment method has its own processing logic. By using the strategy pattern, you can encapsulate the payment processing algorithms for each method, making it easy to add new payment methods without changing the existing code.</p><h3>Conclusion</h3><p>The strategy design pattern provides a clean and maintainable way to encapsulate interchangeable behaviors. It promotes the “open/closed” principle by allowing new algorithms to be added without altering the existing code.</p><p>By implementing the strategy pattern, you can easily switch between different algorithms at runtime, making your system more flexible and easier to maintain.</p><p>You can find the complete code example on <a href="https://github.com/jogiii/all_design_patterns/tree/main/src/main/java/com/design/patterns/creational/strategy">GitHub</a>.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5abd3c3f5e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying the Dependency Inversion Principle in SOLID Design]]></title>
            <link>https://medium.com/@joginder.kumar1991/demystifying-the-dependency-inversion-principle-in-solid-design-c3c43028f7e0?source=rss-e011bad5ed66------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3c43028f7e0</guid>
            <category><![CDATA[solid-design-principles]]></category>
            <category><![CDATA[solid-design]]></category>
            <dc:creator><![CDATA[Joginder Kumar]]></dc:creator>
            <pubDate>Fri, 03 Nov 2023 05:37:05 GMT</pubDate>
            <atom:updated>2023-11-03T05:37:05.845Z</atom:updated>
            <content:encoded><![CDATA[<p>Introduction: In the world of software design, adhering to the SOLID principles is essential to create robust, maintainable, and scalable applications. The last principle in the SOLID group is the Dependency Inversion Principle (DIP), and it’s a fundamental concept for building flexible and loosely coupled systems. In this article, we will explore the Dependency Inversion Principle, understand its importance, and see how it can revolutionize your code design.</p><h3>Unveiling the Dependency Inversion Principle</h3><p>The Dependency Inversion Principle, often referred to as DIP, is the brainchild of Robert C. Martin, also known as Uncle Bob. It consists of two fundamental parts, each of which plays a significant role in decoupling high-level and low-level modules and promoting clean code architecture.</p><ol><li>High-level modules should not depend on low-level modules. Instead, both should depend on abstractions.</li><li>Abstractions should not depend on details. Rather, details should depend on abstractions.</li></ol><p>At first glance, this principle might seem a bit perplexing, but we’ll break it down into more digestible concepts.</p><h3>Understanding Dependencies</h3><p>Before delving into the Dependency Inversion Principle, let’s grasp the notion of “dependencies.” In a software context, dependencies are the components, modules, or objects that your code relies on to function correctly. They are the building blocks that provide necessary functionality. To put it simply, if your code needs something to perform its task, that something is a dependency.</p><p>For example, consider a method that generates a report in JSON format and writes it to disk. The dependencies for this function include:</p><ol><li>An object or module that can convert data to JSON.</li><li>A class, such as FileWriter, that handles writing data to the disk.</li></ol><p>These dependencies are essential to execute the functionality this method provides.</p><h3>Dependency Inversion: A New Perspective</h3><p>Traditionally, when you’re writing a method or code block, you tend to create instances of the necessary objects or modules within that code. In other words, you directly depend on concrete classes. However, doing this tightly couples your high-level module to specific low-level implementations.</p><p>Suppose someone wants to change the report format to XML or post the report to a server instead of writing it to disk. In this scenario, you’d need to modify the existing code, potentially introducing bugs or unwanted side effects.</p><p>The Dependency Inversion Principle advocates a different approach. It suggests that high-level modules (modules that implement business rules) should not be tightly coupled to low-level modules (basic functionalities that can be used across the application). Instead, both should depend on abstractions.</p><p>Abstractions, in this context, can be as simple as interfaces. By defining interfaces for required functionalities (such as writing data or formatting), you allow high-level modules to rely on these interfaces rather than concrete classes. This introduces flexibility into your code.</p><h3>Implementing Dependency Inversion</h3><p>Let’s illustrate the Dependency Inversion Principle with an example. Suppose we have a high-level module responsible for generating reports, and we want it to depend on abstractions rather than concrete classes.</p><p>We can create interfaces like Writer and Formatter that represent the necessary functionalities. The high-level module can then accept the parameters of these interfaces, making it independent of specific implementations.</p><p>When someone needs a report in a different format or delivered through a different medium, they provide their own implementation of the Formatter or Writer interface. This way, your high-level module remains flexible and adaptable without modifying existing code.</p><pre>// Abstraction Interfaces<br>interface Formatter {<br>    String formatReport(Report report);<br>}<br><br>interface Writer {<br>    void writeReport(String formattedReport);<br>}<br><br>// Concrete Implementations<br>class JSONFormatter implements Formatter {<br>    @Override<br>    public String formatReport(Report report) {<br>        // JSON formatting logic<br>        return &quot;{\&quot;title\&quot;: \&quot;&quot; + report.getTitle() + &quot;\&quot;, \&quot;content\&quot;: \&quot;&quot; + report.getContent() + &quot;\&quot;}&quot;;<br>    }<br>}<br><br>class XMLFormatter implements Formatter {<br>    @Override<br>    public String formatReport(Report report) {<br>        // XML formatting logic<br>        return &quot;&lt;report&gt;&lt;title&gt;&quot; + report.getTitle() + &quot;&lt;/title&gt;&lt;content&gt;&quot; + report.getContent() + &quot;&lt;/content&gt;&lt;/report&gt;&quot;;<br>    }<br>}<br><br>class FileWriter implements Writer {<br>    @Override<br>    public void writeReport(String formattedReport) {<br>        // Writing to a file logic<br>        // In a real application, you would write to a file here<br>        System.out.println(&quot;Writing to a file: &quot; + formattedReport);<br>    }<br>}<br><br>class HttpPoster implements Writer {<br>    @Override<br>    public void writeReport(String formattedReport) {<br>        // HTTP POST logic<br>        // In a real application, you would send the data over HTTP here<br>        System.out.println(&quot;Sending report via HTTP: &quot; + formattedReport);<br>    }<br>}<br><br>class Report {<br>    private final String title;<br>    private final String content;<br><br>    public Report(String title, String content) {<br>        this.title = title;<br>        this.content = content;<br>    }<br><br>    public String getTitle() {<br>        return title;<br>    }<br><br>    public String getContent() {<br>        return content;<br>    }<br>}<br><br>class ReportGenerator {<br>    private final Formatter formatter;<br>    private final Writer writer;<br><br>    public ReportGenerator(Formatter formatter, Writer writer) {<br>        this.formatter = formatter;<br>        this.writer = writer;<br>    }<br><br>    public void generateReport(Report report) {<br>        String formattedReport = formatter.formatReport(report);<br>        writer.writeReport(formattedReport);<br>    }<br>}<br><br>public class Main {<br>    public static void main(String[] args) {<br>        Report report = new Report(&quot;SOLID Principles&quot;, &quot;Understanding the Dependency Inversion Principle.&quot;);<br><br>        // Generate and save a report in JSON format<br>        Formatter jsonFormatter = new JSONFormatter();<br>        Writer fileWriter = new FileWriter();<br>        ReportGenerator jsonReportGenerator = new ReportGenerator(jsonFormatter, fileWriter);<br>        jsonReportGenerator.generateReport(report);<br><br>        // Generate and save a report in XML format<br>        Formatter xmlFormatter = new XMLFormatter();<br>        Writer httpPoster = new HttpPoster();<br>        ReportGenerator xmlReportGenerator = new ReportGenerator(xmlFormatter, httpPoster);<br>        xmlReportGenerator.generateReport(report);<br>    }<br>}<br></pre><h3>Conclusion</h3><p>The Dependency Inversion Principle is a key pillar of SOLID design principles. By following DIP, you create code that is decoupled, flexible, and easy to maintain. High-level modules become less reliant on specific low-level implementations, reducing the risk of introducing errors when changes are required.</p><p>When practicing DIP, you are essentially inviting external entities to provide the dependencies your high-level modules need. This design approach promotes clean code and ensures that your software can adapt to new requirements and challenges.</p><p>In a nutshell, embrace the Dependency Inversion Principle to build software that is resilient, extendable, and free from unnecessary coupling.</p><p>Stay tuned for our next article, where we’ll delve into an example that demonstrates the Dependency Inversion Principle in action.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3c43028f7e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the Liskov Substitution Principle in Object-Oriented Programming]]></title>
            <link>https://medium.com/@joginder.kumar1991/understanding-the-liskov-substitution-principle-in-object-oriented-programming-d04623b15c83?source=rss-e011bad5ed66------2</link>
            <guid isPermaLink="false">https://medium.com/p/d04623b15c83</guid>
            <category><![CDATA[solid-design]]></category>
            <category><![CDATA[solid-design-principles]]></category>
            <dc:creator><![CDATA[Joginder Kumar]]></dc:creator>
            <pubDate>Tue, 31 Oct 2023 07:38:40 GMT</pubDate>
            <atom:updated>2023-10-31T07:38:40.572Z</atom:updated>
            <content:encoded><![CDATA[<p>Introduction: In the world of software design, adhering to solid principles is crucial to ensure clean, maintainable, and reliable code. The Liskov Substitution Principle, one of the SOLID principles, is a key guideline for designing classes and objects in a way that guarantees proper behavior. In this article, we’ll dive into the Liskov Substitution Principle and explore its significance using a Java example involving rectangles and squares.</p><h3>The Liskov Substitution Principle (LSP) Demystified</h3><p>The Liskov Substitution Principle, or LSP for short, is the third principle in the SOLID acronym. It dictates that a subclass or derived class should be usable wherever its base class or parent class is expected. This substitution should not change or compromise the desired behavior of the program.</p><p>In essence, LSP ensures that any code that relies on a base class should remain unaffected when a derived class is substituted in its place. This principle isn’t limited to adhering to language syntax; it also encompasses behavioral subtyping, where the behavior of a derived class must align with the behavior expected of its base class.</p><p>To truly grasp LSP, let’s delve into a practical Java example that demonstrates its implications.</p><h3>The Liskov Substitution Principle in Action</h3><p>To understand LSP, we turn to a classic example involving rectangles and squares. While this may seem like a simple geometric case, it brilliantly illustrates the importance of adhering to LSP.</p><h3>The Rectangle and Square Relationship</h3><p>In geometry, we learn that a square is a special type of rectangle. Both have four sides, but squares have the unique property that all their sides are of equal length. Translating this relationship into Java, we might create classes as follows:</p><pre>class Rectangle {<br>    private int width;<br>    private int height;<br><br>    public Rectangle(int width, int height) {<br>        this.width = width;<br>        this.height = height;<br>    }<br><br>    public int getWidth() {<br>        return width;<br>    }<br><br>    public int getHeight() {<br>        return height;<br>    }<br><br>    public int computeArea() {<br>        return width * height;<br>    }<br>}<br><br>class Square extends Rectangle {<br>    public Square(int side) {<br>        super(side, side);<br>    }<br>    <br>    @Override<br>    public void setWidth(int width) {<br>        super.setWidth(width);<br>        super.setHeight(width);<br>    }<br><br>    @Override<br>    public void setHeight(int height) {<br>        super.setWidth(height);<br>        super.setHeight(height);<br>    }<br>}</pre><p>In this example, Rectangle is the base class, and Square is derived from it, as squares are a special case of rectangles with equal width and height. However, by overriding the setWidth and setHeight methods in the Square class to enforce equal dimensions, we inadvertently violate the Liskov Substitution Principle.</p><h3>Violation of Liskov Substitution Principle</h3><p>The violation of LSP becomes apparent when we attempt to use a Square object in a method designed for rectangles. Consider the following code:</p><pre>void useRectangle(Rectangle rect) {<br>    rect.setWidth(20);<br>    rect.setHeight(30);<br>}<br><br>public static void main(String[] args) {<br>    Rectangle rectangle = new Rectangle(10, 15);<br>    Square square = new Square(12);<br><br>    useRectangle(rectangle); // Works as expected<br>    useRectangle(square); // Violates LSP<br>}</pre><p>While using a Rectangle object works as expected, using a Square object violates LSP because it disrupts the behavior expected of a rectangle. This misalignment can lead to unexpected results and erroneous code.</p><h3>Resolving the Liskov Substitution Principle Violation</h3><p>To uphold LSP and prevent such violations, we can take a different approach by introducing an interface, Shape, that defines common behavior:</p><pre>interface Shape {<br>    int computeArea();<br>}<br><br>class Rectangle implements Shape {<br>    private int width;<br>    private int height;<br><br>    public Rectangle(int width, int height) {<br>        this.width = width;<br>        this.height = height;<br>    }<br><br>    public int getWidth() {<br>        return width;<br>    }<br><br>    public int getHeight() {<br>        return height;<br>    }<br><br>    @Override<br>    public int computeArea() {<br>        return width * height;<br>    }<br>}<br><br>class Square implements Shape {<br>    private int side;<br><br>    public Square(int side) {<br>        this.side = side;<br>    }<br><br>    public int getSide() {<br>        return side;<br>    }<br><br>    @Override<br>    public int computeArea() {<br>        return side * side;<br>    }<br>}</pre><p>Now, both Rectangle and Square implement the Shape interface, ensuring that they adhere to the same behavior, without violating LSP.</p><h3>Conclusion</h3><p>The Liskov Substitution Principle is a fundamental concept in object-oriented programming, emphasizing the importance of maintaining expected behavior when substituting derived classes for their base classes. By carefully designing class hierarchies and adhering to interface-based contracts, we can create code that aligns with LSP, leading to more robust and predictable software.</p><p>In the world of programming, understanding and respecting principles like LSP is essential to building software that stands the test of time and remains maintainable and dependable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d04623b15c83" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Applying the Open-Closed Principle in Java: A Simple Example]]></title>
            <link>https://medium.com/@joginder.kumar1991/applying-the-open-closed-principle-in-java-a-simple-example-fb077e6578c0?source=rss-e011bad5ed66------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb077e6578c0</guid>
            <category><![CDATA[solid-design-principles]]></category>
            <category><![CDATA[solid-design]]></category>
            <dc:creator><![CDATA[Joginder Kumar]]></dc:creator>
            <pubDate>Tue, 31 Oct 2023 06:40:44 GMT</pubDate>
            <atom:updated>2023-10-31T06:40:44.436Z</atom:updated>
            <content:encoded><![CDATA[<p>Introduction: In the realm of software design, the SOLID principles serve as a foundation for creating maintainable and scalable code. One of these principles, the Open-Closed Principle, emphasizes the importance of designing software entities to be open for extension but closed for modification. In this article, we’ll explore the Open-Closed Principle using a straightforward Java example, shedding light on how this principle simplifies code maintenance and encourages flexibility.</p><h3>The Open-Closed Principle in a Nutshell</h3><p>The Open-Closed Principle, often referred to as OCP, is a concept built on the bedrock of inheritance in object-oriented programming. It encourages us to design classes and modules that are open to extension, allowing us to add new features or behaviors, while simultaneously being closed to modification, preserving the integrity of existing code.</p><p>Now, let’s dissect this principle with the help of a practical example. Imagine we’re tasked with creating software to manage customers and subscribers for a telecommunications company offering both telephone and internet services.</p><h3>Exploring the Example</h3><p>In our example, we have two primary classes:</p><h3>1. PhoneSubscriber</h3><p>The PhoneSubscriber class represents customers who use the telephone service. It contains properties such as subscriber ID, address, phone number, and a base rate used for calculating the subscriber&#39;s bill. The class also features a simple calculateBill method, which serves demonstration purposes.</p><h3>2. IspSubscriber</h3><p>The IspSubscriber class represents subscribers to the internet service. It shares some common properties with PhoneSubscriber, such as subscriber ID, address, phone number, and a base rate. Additionally, it includes unique properties like the number of bytes allocated at the start of billing and a &quot;free data&quot; feature. Similarly, it features a calculateBill method for demonstration.</p><p>To handle usage data for both services, we’ve introduced two more classes, InternetSessionHistory and CallHistory. These classes capture service usage but are kept simple for illustrative purposes.</p><h3>Identifying Duplications and Challenges</h3><p>Upon closer inspection, you’ll notice that certain properties are common to both PhoneSubscriber and IspSubscriber classes. This duplication can lead to maintenance challenges.</p><p>Furthermore, if the company decides to introduce a new service, such as VoIP, it would involve creating a new class with potential overlaps and variations in properties and billing logic. This could quickly become unwieldy.</p><h3>Implementing the Open-Closed Principle</h3><p>To address these issues, we apply the Open-Closed Principle by creating a solid base class:</p><pre>public abstract class Subscriber {<br><br>    protected Long subscriberId;<br><br>    protected String address;<br><br>    protected Long phoneNumber;<br><br>    protected int baseRate;<br><br>    public Long getSubscriberId() {<br>        return subscriberId;<br>    }<br><br>    public void setSubscriberId(Long subscriberId) {<br>        this.subscriberId = subscriberId;<br>    }<br><br>    public String getAddress() {<br>        return address;<br>    }<br><br>    public void setAddress(String address) {<br>        this.address = address;<br>    }<br><br>    public Long getPhoneNumber() {<br>        return phoneNumber;<br>    }<br><br>    public void setPhoneNumber(Long phoneNumber) {<br>        this.phoneNumber = phoneNumber;<br>    }<br><br>    public int getBaseRate() {<br>        return baseRate;<br>    }<br><br>    public void setBaseRate(int baseRate) {<br>        this.baseRate = baseRate;<br>    }<br><br>    public abstract double calculateBill(); //extension<br><br>}</pre><p>The Subscriber class serves as a foundation, encapsulating common properties and defining an abstract calculateBill method. This method allows child classes to provide their own bill calculation logic, ensuring extensibility.</p><p>Next, we extend the base class to create PhoneSubscriber and IspSubscriber classes. For instance, PhoneSubscriber becomes:</p><pre>public class PhoneSubscriber extends Subscriber {<br><br>    //only for demonstration - open for extension<br>    @Override<br>    public double calculateBill() {<br>        List&lt;CallHistory.Call&gt; sessions = CallHistory.getCurrentCalls(subscriberId);<br>        long totalDuration = sessions.stream().mapToLong(CallHistory.Call::getDuration).sum();<br>        return totalDuration*baseRate/100;<br>    }<br><br>}</pre><pre>public class ISPSubscriber extends Subscriber {<br><br>    private long freeUsage;<br><br>    //only for demonstration<br>    @Override<br>    public double calculateBill() {<br>        List&lt;InternetSessionHistory.InternetSession&gt; sessions = InternetSessionHistory.getCurrentSessions(subscriberId);<br>        long totalData = sessions.stream().mapToLong(InternetSessionHistory.InternetSession::getDataUsed).sum();<br>        long chargeableData = totalData - freeUsage;<br><br>        if(chargeableData &lt;= 0) {<br>            return 0;<br>        }<br>        return chargeableData*baseRate/100;<br>    }<br><br>    /**<br>     * @return the freeUsage<br>     */<br>    public long getFreeUsage() {<br>        return freeUsage;<br>    }<br><br>    /**<br>     * @param freeUsage the freeUsage to set<br>     */<br>    public void setFreeUsage(long freeUsage) {<br>        this.freeUsage = freeUsage;<br>    }<br><br><br>}</pre><p>This change allows us to maintain the common properties and behaviors in a single location (the Subscriber base class) and extend the functionality as needed without modifying the base class.</p><blockquote>For full example use this GitHub link</blockquote><blockquote><a href="https://github.com/jogiii/solid-design-patterns/tree/main/src/main/java/com/design/solid/openclose">https://github.com/jogiii/solid-design-patterns/tree/main/src/main/java/com/design/solid/openclose</a></blockquote><h3>Conclusion</h3><p>The Open-Closed Principle, while simple in concept, has a profound impact on code maintainability and adaptability. By identifying common properties and behaviors and encapsulating them in a base class, we ensure that our code is open for extension and closed for modification. This design principle encourages a clean, scalable, and flexible codebase, allowing for future service additions and modifications with ease.</p><p>As you embark on your software development journey, keep the Open-Closed Principle in mind. By adhering to this principle, you’ll create software that stands the test of time and is well-prepared for future expansions and changes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb077e6578c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the Open-Closed Principle in Object-Oriented Programming]]></title>
            <link>https://medium.com/@joginder.kumar1991/understanding-the-open-closed-principle-in-object-oriented-programming-c6230e64e998?source=rss-e011bad5ed66------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6230e64e998</guid>
            <category><![CDATA[solid-design]]></category>
            <category><![CDATA[solid-design-principles]]></category>
            <dc:creator><![CDATA[Joginder Kumar]]></dc:creator>
            <pubDate>Tue, 31 Oct 2023 06:21:10 GMT</pubDate>
            <atom:updated>2023-10-31T06:42:45.656Z</atom:updated>
            <content:encoded><![CDATA[<p>Introduction: In the world of software development, there are principles that guide us in writing clean, maintainable, and efficient code. One of these principles, which plays a crucial role in object-oriented programming, is the Open-Closed Principle. In this article, we’ll delve into the Open-Closed Principle, explain what it means, and how it can be applied in Java.</p><h3>The Open-Closed Principle — A Closer Look</h3><p>The Open-Closed Principle, often abbreviated as OCP, is one of the SOLID design principles. It states that software entities, which encompass classes, modules, or methods, should be open for extension but closed for modification. At first glance, this principle may appear cryptic, but with the right context, it becomes remarkably simple to understand.</p><h3>Open for Extension</h3><p>When we say a software entity is “open for extension,” it means that we should have the ability to enhance or extend its existing behavior. In the realm of Java and object-oriented programming, this principle becomes clear.</p><p>Imagine a scenario where you have a base class that is already written and thoroughly tested. You find that you need to modify or extend the behavior of a method within this class. The Open-Closed Principle encourages us to do this without altering the existing code in the base class. Instead, we can achieve this extension by using inheritance.</p><h3>Closed for Modification</h3><p>The “closed for modification” aspect of the principle emphasizes that once a software entity, such as a base class, is in place and functioning as intended, we should avoid making any changes to its code. The code within the base class is considered pristine and has been rigorously tested. Modifying it can introduce unforeseen issues and disrupt the stability of the software.</p><h3>Applying the Open-Closed Principle in Java</h3><p>To apply the Open-Closed Principle in Java, we start with a base class that contains well-tested code. When the need arises to extend or modify the behavior of this class, we refrain from directly altering the base class. Instead, we create a new class that extends the base class and overrides the methods we want to change. This allows us to maintain the integrity of the original code while adding new functionality.</p><p>Here’s a simple Java example to illustrate the Open-Closed Principle in action:</p><pre>class BaseClass {<br>    public void performAction() {<br>        // Existing code<br>    }<br>}<br><br>class ExtendedClass extends BaseClass {<br>    @Override<br>    public void performAction() {<br>        super.performAction(); // Call the base class method<br>        // Add new behavior here<br>    }<br>}<br></pre><p>In this example, the BaseClass is closed for modification, ensuring that its existing functionality remains intact. To extend or modify its behavior, we create the ExtendedClass by inheriting from the BaseClass and overriding the performAction method.</p><p>By adhering to the Open-Closed Principle, we can maintain and evolve our codebase without introducing unnecessary risks.</p><blockquote>For the application for open close principle use below article</blockquote><blockquote><a href="https://medium.com/@joginder.kumar1991/applying-the-open-closed-principle-in-java-a-simple-example-fb077e6578c0">https://medium.com/@joginder.kumar1991/applying-the-open-closed-principle-in-java-a-simple-example-fb077e6578c0</a></blockquote><h3>Conclusion</h3><p>The Open-Closed Principle is a fundamental concept in object-oriented programming that encourages us to design software entities that are open for extension while remaining closed for modification. By following this principle, we can write code that is more robust, maintainable, and adaptable, allowing our software to grow and evolve without disrupting its existing functionality. In Java and many other programming languages, this principle can be applied through the power of inheritance and method overriding.</p><p>Incorporating the Open-Closed Principle into your development process is a step towards creating cleaner, more efficient, and more maintainable software. As you continue your journey in software development, keep in mind the value of this principle in crafting elegant and resilient code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6230e64e998" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying the Single Responsibility Principle in Software Design]]></title>
            <link>https://medium.com/@joginder.kumar1991/demystifying-the-single-responsibility-principle-in-software-design-149192d64a46?source=rss-e011bad5ed66------2</link>
            <guid isPermaLink="false">https://medium.com/p/149192d64a46</guid>
            <category><![CDATA[solid-design-principles]]></category>
            <dc:creator><![CDATA[Joginder Kumar]]></dc:creator>
            <pubDate>Mon, 30 Oct 2023 12:15:30 GMT</pubDate>
            <atom:updated>2023-10-31T05:16:31.844Z</atom:updated>
            <content:encoded><![CDATA[<p>When it comes to designing software that’s maintainable, robust, and easy to understand, adhering to solid design principles is a must. One of these fundamental principles is the Single Responsibility Principle (SRP), which is the ‘S’ in SOLID, an acronym for a set of five design principles aimed at making software more modular and scalable.</p><p><strong>What is the Single Responsibility Principle?</strong></p><blockquote>In essence, the SRP states that “there should never be more than one reason for a class to change.” At first glance, this definition might seem a bit abstract, but it’s straightforward when you break it down. The term “single responsibility” implies that a class should focus on a very specific functionality or address a particular concern within the software system.</blockquote><p>To illustrate this principle, let’s consider an example. Imagine you’ve written a class that creates and sends a message to a remote server listening on a specific port. This class performs multiple tasks, such as managing communication protocols, formatting the message, and handling authentication.</p><p><strong>The Pitfall of Violating SRP</strong></p><p>Now, let’s examine why this scenario violates the SRP. Since this class takes on several responsibilities, it becomes susceptible to change for various reasons. If the communication protocol changes, the class needs to be modified. Similarly, if the message format changes from JSON to XML or if new parameters like authentication are added for security, the class requires adjustments.</p><p>In this example, you can see that multiple reasons exist for the class to change. This is precisely what the SRP advises against. The principle emphasizes that when a class takes on more than one responsibility, it becomes less maintainable and more challenging to manage. It leads to situations where a minor change in one area of the class can inadvertently affect other parts, making code modifications complex and error-prone.</p><p><strong>Embracing the Single Responsibility Principle</strong></p><p>To adhere to the SRP, you should design your classes and modules with a clear and specific focus. If you have three distinct responsibilities, you should create three separate classes or modules to handle each of them. By doing so, when changes are needed, they can be executed in an organized manner. No longer will you find yourself delving into a convoluted method just to alter a message format from JSON to XML.</p><p>Here’s a textual representation of the classes and their responsibilities:</p><pre>------------------------       ----------------------------<br>|   MessageSender     |       |   MessageFormatter       |<br>|----------------------|       |---------------------------|<br>|                      |       |                           |<br>| - send(message)      |       | - formatMessage(message) |<br>| - setProtocol(proto) |       | - setFormat(format)      |<br>| - setAuth(auth)      |       |                           |<br>|                      |       |                           |<br>------------------------       ----------------------------<br><br>-------------------------<br>| CommunicationProtocol |<br>|-----------------------|<br>|                       |<br>| - setProtocol(proto)  |<br>|                       |<br>-------------------------<br></pre><p>In this representation:</p><p><strong>MessageSender</strong> is a class responsible for sending messages to a remote server.</p><p><em>It has a send method for sending messages.<br>It has methods for setting the communication protocol and authentication.</em></p><p><strong>MessageFormatter</strong> is a class responsible for formatting messages.</p><p><em>It has a formatMessage method for formatting messages.<br>It has methods for setting the message format.</em></p><p><strong>CommunicationProtocol</strong> is a class that handles communication protocol details.</p><p><em>It has a method for setting the protocol.</em></p><p>In summary, the Single Responsibility Principle is all about designing software in a way that ensures each class or module tackles a single, well-defined concern. This practice simplifies code maintenance, reduces the risk of introducing unintended side effects, and makes your software more adaptable to change.</p><p>In your journey as a software developer, remember to keep the SRP in mind as a guiding principle to create more robust and manageable software systems. Your codebase will thank you for it.</p><blockquote>Please refer this GitHub repository for hands-on implementation</blockquote><blockquote><a href="https://github.com/jogiii/solid-design-patterns/tree/main/src/main/java/com/design/solid/singleresponsibility">https://github.com/jogiii/solid-design-patterns/tree/main/src/main/java/com/design/solid/singleresponsibility</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=149192d64a46" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reverse an Array in Java]]></title>
            <link>https://medium.com/@joginder.kumar1991/reverse-an-array-in-java-e5f785f7327f?source=rss-e011bad5ed66------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5f785f7327f</guid>
            <category><![CDATA[datastrucutre]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[arrays]]></category>
            <dc:creator><![CDATA[Joginder Kumar]]></dc:creator>
            <pubDate>Sun, 20 Mar 2022 17:59:52 GMT</pubDate>
            <atom:updated>2022-03-20T17:59:52.857Z</atom:updated>
            <content:encoded><![CDATA[<pre>public class ReverseArray {<br><br>    static void reverseArray(int arr[]){<br>        int start =0;<br>        int end = arr.length-1;<br>        int temp;<br><br><br>        while(start&lt;end){<br>            temp=arr[start];<br>            arr[start]=arr[end];<br>            arr[end]=temp;<br><br>            start++;<br>            end--;<br>        }<br>        <br>    }<br><br>    static void printArray(int arr[])<br>    {<br>        for (int i = 0; i &lt; arr.length; i++)<br>            System.<em>out</em>.print(arr[i] + &quot; &quot;);<br><br>        System.<em>out</em>.println();<br>    }<br><br>    public static void main(String[] args) {<br><br>        int arr[] = {1, 2, 3, 4, 5, 6};<br>        <em>reverseArray</em>(arr);<br><br>        <em>printArray</em>(arr);<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5f785f7327f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bubble Sort Algorithm using Java]]></title>
            <link>https://medium.com/@joginder.kumar1991/bubble-sort-algorithm-using-java-a18379775ab8?source=rss-e011bad5ed66------2</link>
            <guid isPermaLink="false">https://medium.com/p/a18379775ab8</guid>
            <category><![CDATA[time-complexity]]></category>
            <category><![CDATA[data-structure-algorithm]]></category>
            <category><![CDATA[bubble-sort-algorithm]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Joginder Kumar]]></dc:creator>
            <pubDate>Sun, 20 Mar 2022 17:06:53 GMT</pubDate>
            <atom:updated>2022-03-20T17:06:53.384Z</atom:updated>
            <content:encoded><![CDATA[<p>Today I am going to explain, one of the most basic sorting algorithms, called bubble sort.</p><p>Bubble Sort compares all the elements one by one and sorts them based on their values</p><p>If the given array has to be sorted in ascending order, then bubble sort will start by comparing the first element of the array with the second element, if the first element is greater than the second element, it will swap both the elements, and then move on to compare the second and the third element, and so on.</p><p>If we have total <strong>n </strong>elements, then we need to repeat this process for <strong>n-1</strong> times</p><h3>Time Complexity</h3><h3>O(n2)</h3><h3><strong>Algorithm</strong></h3><p>The bubble sort algorithm consists of 3 steps</p><ol><li>Start with the first element(index = 0), compare the current element with the next element of the array.</li><li>If the current element is greater than the next element of the array, swap them.</li><li>If the current element is less than the next element, move to the next element. Repeat Step 1.</li></ol><p>Simple :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*f9ahYHdFigd-wsCSJF2uig.png" /></figure><h3><strong>Code:</strong></h3><pre>public class BubbleSort {<br>    public static void main(String[] args) {<br>        int[] intArray= {1, 23,10,-2};</pre><pre><em>//once the single loop end you bubble out the highest value to last //index</em><br>        for(int lastUnsortedIndex = intArray.length-1; lastUnsortedIndex&gt;0;lastUnsortedIndex--){<br>            for(int i=0;i&lt;lastUnsortedIndex;i++){<strong>//step 1</strong><br>                if(intArray[i]&gt;intArray[i+1])<br>                    <em>swap</em>(intArray, i, i+1);<strong>//step 2</strong><br>            }<br>        }</pre><pre>//this is to print out the array</pre><pre>        for(int i =0;i&lt;intArray.length;i++){<br>            System.<em>out</em>.println(intArray[i]);<br>        }<br>    }</pre><pre>//swap method for swapping :P<br>    public static void swap(int[] array, int i, int j){<br>        if(i==j)//if both of them are equal, then no need to swap<br>            return;<br><br>        int temp = array[i];<br>        array[i] = array[j];<br>        array[j] = temp;<br><br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a18379775ab8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>