<?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 Aditya on Medium]]></title>
        <description><![CDATA[Stories by Aditya on Medium]]></description>
        <link>https://medium.com/@iamadityaraj04?source=rss-a9ae2a53459c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*4XPU6_eNrOAsAWHG42d9MA.png</url>
            <title>Stories by Aditya on Medium</title>
            <link>https://medium.com/@iamadityaraj04?source=rss-a9ae2a53459c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 14:33:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@iamadityaraj04/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 the Singleton Pattern in Java — With Thread-Safety, Serialization & Cloning]]></title>
            <link>https://iamadityaraj04.medium.com/mastering-the-singleton-pattern-in-java-with-thread-safety-serialization-cloning-2ab19d99e9d7?source=rss-a9ae2a53459c------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ab19d99e9d7</guid>
            <category><![CDATA[singleton-pattern]]></category>
            <category><![CDATA[desing-pattern]]></category>
            <category><![CDATA[singleton]]></category>
            <category><![CDATA[singleton-design-pattern]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Aditya]]></dc:creator>
            <pubDate>Mon, 21 Jul 2025 09:25:06 GMT</pubDate>
            <atom:updated>2025-07-23T16:30:06.566Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mastering the Singleton Pattern in Java — With Thread-Safety, Serialization &amp; Cloning</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yNqWEoBEzG0rW4PmMx39tw.png" /></figure><h3>Introduction</h3><p>The Singleton Pattern ensures that a class has <strong>only one instance</strong> and provides a global point of access to it.</p><p>In this post, we’ll explore how to implement a <strong>robust Singleton class in Java</strong> :</p><ul><li>Thread-safe</li><li>Resistant to reflection attacks</li><li>Immutable to cloning</li><li>Secure during serialization/deserialization</li></ul><h3>What is the Singleton Pattern?</h3><p>A <strong>Singleton</strong> is a class that allows only <strong>one instance</strong> of itself to be created and gives access to that instance through a globally accessible method.</p><p>Use cases include:</p><ul><li>Configuration classes</li><li>Database connection pools</li><li>Caches</li><li>Loggers</li></ul><h3>Eager vs Lazy Initialization in Singleton Pattern</h3><p>When designing a Singleton, choosing between <strong>eager</strong> and <strong>lazy</strong> initialization depends on your application’s performance and resource management needs.</p><h4>🔹 Eager Initialization</h4><p>In eager initialization, the Singleton instance is created at the time of <strong>class loading</strong>, whether or not it is actually used.</p><p><em>Example:</em></p><pre>public class EagerSingleton {<br>    private static final EagerSingleton instance = new EagerSingleton();<br>private EagerSingleton() {}<br>    public static EagerSingleton getInstance() {<br>        return instance;<br>    }<br>}</pre><p>✅ Pros:</p><ul><li>Simple and thread-safe (JVM ensures thread-safety during class loading).</li><li>No synchronization overhead.</li></ul><p>❌ Cons:</p><ul><li>Instance is created even if the application <strong>never uses</strong> it.</li><li>Not ideal when the Singleton is <strong>resource-heavy</strong>.</li></ul><h4>🔹 Lazy Initialization</h4><p>In lazy initialization, the Singleton instance is created <strong>only when it is needed</strong>, not at class loading.</p><h4>Lazy Singleton (Not Thread-Safe)</h4><pre>public class LazySingleton {<br>    private static LazySingleton instance;<br>private LazySingleton() {}<br>    public static LazySingleton getInstance() {<br>        if (instance == null) {<br>            instance = new LazySingleton();<br>        }<br>        return instance;<br>    }<br>}</pre><p>This is fine in a single-threaded environment, but <strong>breaks under concurrency</strong>.</p><h3>Final Implementation</h3><pre>import java.io.Serializable;<br><br>public class Singleton implements Cloneable, Serializable {<br><br>    private static final long serialVersionUID = 1L;<br>    private static volatile Singleton singletonObj;<br><br>    private Singleton() {<br>        if(singletonObj != null){<br>            throw new IllegalStateException(&quot;Singleton object has been already created&quot;);<br>        }<br>    }<br><br>    public static Singleton getSingletonInstance(){<br>        if(singletonObj == null){<br>            synchronized (Singleton.class){<br>                if(singletonObj == null){<br>                    singletonObj =  new Singleton();<br>                }<br>            }<br>        }<br>        return  singletonObj;<br>    }<br><br>    @Override<br>    public Object clone() throws CloneNotSupportedException {<br>        throw new CloneNotSupportedException(&quot;Singleton class can not be cloned.&quot;);<br>    }<br><br>    protected Object readResolve(){<br>        return getSingletonInstance();<br>    }<br>}</pre><h3>Key Features</h3><h4>1. volatile Keyword</h4><p>Ensures <strong>visibility and ordering</strong> of writes to the singletonObj across threads.</p><h4>2. Double-Checked Locking</h4><p>Reduces the performance overhead of acquiring a lock <strong>by synchronizing only on the first access</strong>.</p><pre>public static Singleton getSingletonInstance(){<br>    if(singletonObj == null){<br>          synchronized (Singleton.class){<br>            if(singletonObj == null){<br>                singletonObj =  new Singleton();<br>            }<br>        }<br>    }<br>    return  singletonObj;<br>}</pre><h4>3. Preventing Cloning</h4><p>If a class implements Cloneable, it can be cloned using .clone(). We override clone() to prevent this.</p><pre>@Override<br>public Object clone() throws CloneNotSupportedException {<br>    throw new CloneNotSupportedException(&quot;Singleton class can not be cloned.&quot;);<br>}</pre><h4>4. Preventing Multiple Instances During Deserialization</h4><p>Without readResolve(), deserializing a Singleton class would create a <strong>new instance</strong>.</p><pre>protected Object readResolve(){<br>    return getSingletonInstance();<br>}</pre><p>This ensures that even during deserialization, the same instance is returned.</p><h4>5. Blocking Reflection</h4><p>Reflection can break Singleton by accessing the private constructor. You can guard against this in the constructor:</p><pre>private Singleton() {<br>    if(singletonObj != null){<br>        throw new IllegalStateException(&quot;Singleton object has been already created&quot;);<br>    }<br>}</pre><p>However, <strong>reflection can still bypass this check</strong> using setAccessible(true) — consider using enums for the most robust defense.</p><h3>The Ultimate Singleton: Enum</h3><p>If you’re not concerned about lazy-loading, the best way to implement a Singleton in Java is using an enum.</p><pre>public enum EnumSingleton {<br>    INSTANCE;<br>public void doSomething() {<br>        // business logic<br>    }<br>}</pre><h3>Conclusion</h3><p><strong>Correct and production-grade implementation </strong>of singleton requires awareness of Java-specific pitfalls:</p><ul><li>Thread-safety</li><li>Cloning</li><li>Serialization</li><li>Reflection</li></ul><p>By handling all of these concerns as shown, you can build a robust Singleton class.</p><h3>Thanks for Reading! 🙏</h3><p>If you found this article helpful, give it a clap 👏 and share it with others who might benefit from it.</p><p>Let’s connect on LinkedIn: <a href="https://www.linkedin.com/in/iamadityaraj04/">https://www.linkedin.com/in/iamadityaraj04/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ab19d99e9d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ACID VS BASE in DBMS]]></title>
            <link>https://iamadityaraj04.medium.com/acid-vs-base-in-dbms-12b62d8237f6?source=rss-a9ae2a53459c------2</link>
            <guid isPermaLink="false">https://medium.com/p/12b62d8237f6</guid>
            <category><![CDATA[base-property]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[dbms]]></category>
            <category><![CDATA[acid-properties]]></category>
            <dc:creator><![CDATA[Aditya]]></dc:creator>
            <pubDate>Mon, 31 Mar 2025 18:39:24 GMT</pubDate>
            <atom:updated>2025-03-31T18:39:24.578Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*kZoOEqlPLf1kPgdsUqdaPw.png" /></figure><h3><strong>ACID Properties</strong></h3><blockquote><strong>Atomicity: The All-or-Nothing Principle</strong></blockquote><p>Atomicity ensures that a transaction is <strong>fully completed or not executed at all</strong>. If any part of the transaction fails, the entire operation is rolled back, leaving the database in its original state — as if the transaction never happened.</p><p>To achieve this, transaction management systems use <strong>logging and rollback mechanisms</strong> to maintain consistency.</p><h4>Example:</h4><p>Imagine <strong>Person A</strong> is transferring <strong>$500</strong> from <strong>Account 1 to Account 2</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*y9UWtrQmEN2gNRNGhL29tQ.png" /></figure><ul><li>The system <strong>debits $500</strong> from <strong>Acc1</strong>.</li><li>Before the amount is credited to <strong>Acc2</strong>, a system failure occurs.</li></ul><p>With <strong>atomicity</strong>, the transaction <strong>automatically rolls back</strong>, and $500 is <strong>returned to Acc1</strong>, ensuring no partial updates occur.</p><blockquote><strong>Consistency: Maintaining Database Integrity</strong></blockquote><p>Consistency ensures that a transaction <strong>follows all predefined rules and constraints</strong>, leaving the database in a valid state before and after execution. Any data written during a transaction <strong>must adhere to integrity constraints</strong>, preventing corruption or invalid states.</p><h4>Example:</h4><p>Suppose a database enforces a rule that <strong>the total balance across all accounts must remain constant</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*W5aL0mOTtuiDmXCKWYepow.png" /></figure><ul><li>If <strong>$100 is transferred</strong> from <strong>Account A to Account B</strong>, the system ensures that the total balance before ($ 500 + $ 300 = $ 800)and after the transaction ($ 400 + $ 400 = $ 800)<strong>remains the same</strong>.</li><li>If any operation violates this rule (e.g., debiting without crediting), the transaction fails, and changes are rolled back.</li></ul><p>This guarantees that the database <strong>never enters an inconsistent state</strong> due to faulty transactions.</p><blockquote><strong>Isolation: Ensuring Independent Transactions</strong></blockquote><p>Isolation defines how transactions execute <strong>concurrently</strong> without interfering with each other. It ensures that <strong>each transaction operates independently</strong>, preventing data inconsistencies caused by simultaneous operations.</p><p>A database enforces isolation by ensuring that one transaction <strong>does not see the intermediate state</strong> of another transaction. Depending on the <strong>isolation level</strong>, it can prevent issues like <strong>dirty reads, non-repeatable reads, and phantom reads</strong>.</p><h4>Example:</h4><p>Imagine two users trying to <strong>withdraw money from the same bank account simultaneously</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*LIcfb-1W2XsDDd0N0nmicg.png" /></figure><ul><li><strong>User A</strong> initiates a withdrawal of <strong>$100</strong> from Account X.</li><li><strong>User B</strong> also initiates a withdrawal of <strong>$200</strong> from the same account.</li><li>If these transactions <strong>aren’t properly isolated</strong>, they might both check the balance before any deduction is finalized, leading to <strong>over-withdrawal</strong>.</li><li>With proper isolation, the database ensures that <strong>one transaction completes first before the second one is processed</strong>, preventing inconsistencies.</li></ul><p>This ensures <strong>data integrity and prevents conflicts</strong> in concurrent transactions.</p><blockquote><strong>Durability: Ensuring Permanent Changes</strong></blockquote><p>Durability guarantees that <strong>once a transaction is committed, its changes are permanently saved</strong>, even in the event of a system crash, power failure, or hardware issues. This ensures that no committed data is lost.</p><p>To achieve durability, databases use <strong>transaction logs, write-ahead logging (WAL), and backups</strong> to store changes persistently.</p><h4>Example:</h4><p>Suppose a customer <strong>transfers $1000</strong> from Account A to Account B.</p><ul><li>The transaction is <strong>processed and committed</strong>.</li><li>Before the updated balance is displayed, a <strong>power failure occurs</strong>.</li><li>When the system restarts, the database <strong>restores the committed transaction</strong> from logs, ensuring that the <strong>$1000</strong> transfer is not lost.</li></ul><p>This ensures that once a transaction is successfully completed, its effects <strong>remain intact permanently</strong>, regardless of system failures.</p><h3>BASE Properties</h3><blockquote><strong>Basically Available</strong></blockquote><p>The system guarantees <strong>high availability</strong>, ensuring it responds to every request, even if the data provided is temporarily inconsistent. This allows distributed systems to remain operational despite potential delays in data synchronization.</p><h4><strong>Example:</strong></h4><p>On an e-commerce platform, users can add items to their cart even when the inventory database is experiencing high traffic and is momentarily out of sync. The system prioritizes availability, and inventory updates are processed later.</p><blockquote><strong>Soft State</strong></blockquote><p>The system’s state can change over time, even without new transactions, as it allows temporary inconsistencies during data synchronization.</p><h4><strong>Example:</strong></h4><p>On a <strong>social media platform</strong>, a user might temporarily see outdated likes or comments on a post due to delays in synchronization between servers.</p><blockquote><strong>Eventual Consistency</strong></blockquote><p>Rather than enforcing <strong>immediate consistency</strong>, the system ensures that all copies of the data will <strong>synchronize over time</strong>. While temporary discrepancies may occur, consistency is eventually restored.</p><h4><strong>Example:</strong></h4><p>In a <strong>messaging app with a distributed database</strong>, messages sent by one user may initially appear <strong>out of order</strong> for the recipient. However, after a short delay, the system ensures all messages are correctly synchronized across devices.</p><h3>Thanks for Reading! 🙏</h3><p>If you found this article helpful, please give it a clap 👏 and share it with others who might benefit from it.</p><p>Follow me on <a href="https://www.linkedin.com/in/iamadityaraj04/">LinkedIn</a> and <a href="https://medium.com/@iamadityaraj04">Medium</a> for more insights on software development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12b62d8237f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SOLID Principles With Examples In Java]]></title>
            <link>https://iamadityaraj04.medium.com/solid-principles-with-examples-in-java-3ef5a3e8d402?source=rss-a9ae2a53459c------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ef5a3e8d402</guid>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[solid-principles-in-java]]></category>
            <category><![CDATA[solid-principles]]></category>
            <dc:creator><![CDATA[Aditya]]></dc:creator>
            <pubDate>Sat, 22 Mar 2025 20:16:52 GMT</pubDate>
            <atom:updated>2025-03-22T20:16:52.236Z</atom:updated>
            <content:encoded><![CDATA[<h3>SOLID Principles with examples</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z2JQfCjuuvk3VjpDmEGnEw.png" /></figure><h3>1. Single Responsibility Principle (SRP)</h3><p>The Single Responsibility Principle (SRP) states that <strong>a class or module should have only one reason to change.</strong> This means it should have a single responsibility or purpose, encapsulating all aspects that change for the same reasons and separating those that change for different reasons.</p><h3>Bad Example</h3><p>Consider a simple <strong>Employee</strong> class that manages employee data and payroll processing. Initially, it might look like this:</p><pre>public class Employee {<br>    private String name;<br>    private double salary;<br>    <br>    public Employee(String name, double salary) {<br>        this.name = name;<br>        this.salary = salary;<br>    }<br>    public void saveEmployeeToDatabase() {<br>        *// save employee data to a database*<br>    }<br>    public void calculatePayroll() {<br>        *// calculate payroll based on salary*<br>    }<br>    public void sendPayrollReport() {<br>        *// send payroll report via email*<br>    }<br>}</pre><p><strong>Violation of SRP</strong></p><p>In this example, the <strong>Employee</strong> class violates the SRP because it has multiple responsibilities:</p><ul><li>Saving employee data to a database.</li><li>Calculating payroll.</li><li>Sending payroll reports.</li></ul><h3>Solution</h3><pre>public class Employee {<br>    private String name;<br>    private double salary;<br>    <br>    public Employee(String name, double salary) {<br>        this.name = name;<br>        this.salary = salary;<br>    }<br>    public String getName() {<br>        return name;<br>    }<br>    public double getSalary() {<br>        return salary;<br>    }<br>}<br>public class EmployeeRepository {<br>    public void saveEmployeeToDatabase(Employee employee) {<br>        *// Logic to save employee data to a database*<br>    }<br>}<br>public class PayrollCalculator {<br>    public double calculatePayroll(Employee employee) {<br>        *// Logic to calculate payroll based on salary*<br>    }<br>}<br>public class PayrollReporter {<br>    public void sendPayrollReport(Employee employee, double payroll) {<br>        *// Logic to send payroll report via email*<br>    }<br>}</pre><p><strong>Benefits</strong></p><p>By applying the SRP:</p><ul><li>Each class has a single responsibility and reason to change.</li><li>Changes to one responsibility do not affect others.</li><li>The code becomes more modular, maintainable, and scalable.</li></ul><h3>2. Open/Close Principle (OCP)</h3><p>The <strong>Open-Closed Principle (OCP)</strong> states that software entities, such as classes, modules, or functions, should be <strong>open for extension</strong> but <strong>closed for modification</strong>. This means that you should be able to add new functionality to an existing system without altering its underlying structure or code.</p><p><strong>Violation of OCP</strong></p><h3>Bad Example</h3><ul><li>Let suppose there is a class named as Test which is responsible to save Invoice to a database.</li></ul><pre>public class Test {<br>    Invoice invoice;<br>    public Test (Invoice invoice){<br>        this.invoice  = invoice;<br>    }<br>    <br>    public void  saveToDB1(){<br>        //save invoice to the db<br>    }<br>}</pre><p>Now, let suppose we want to add one more functionality which will save the same data to another db.</p><pre>public class Test {<br>    Invoice invoice;<br>    public Test (Invoice invoice){<br>        this.invoice  = invoice;<br>    }<br>    public void  saveToDB1(){<br>        //save invoice to db1<br>    }<br>    <br>    public void saveToDB2(){<br>      //save invoice to db2<br>   }<br>}</pre><p>but above snippet violates our principle because class should not be modified because it could create unnecessary errors.</p><h3>Solution</h3><ul><li>will create an interface and 2 diff class which will implements the functionality to save to db’s accordingly.</li><li>In this case we didn’t made any modification to db1 implementations</li></ul><pre>interface Test {<br>    public void save(Invoice invoice);<br>}<br><br>class SaveToDB1 implements Test{<br>    public void save(Invoice invoice){<br>        // save to db1<br>    }<br>}<br>class SaveToDB2 implements Test{<br>    public void save(Invoice invoice){<br>        // save to db2<br>    }<br>}</pre><p><strong>Benefits</strong></p><ul><li><strong>Reduced Bugs</strong>: By not modifying existing code, you minimize the risk of introducing new bugs.</li><li><strong>Easier Maintenance</strong>: Adding new features without altering existing code makes maintenance easier and less risky.</li><li><strong>Flexibility</strong>: It allows for the extension of functionalities without disrupting the stability of the system.</li></ul><h3>3. Liskov Substitution Principle (LSP)</h3><p>The <strong>Liskov Substitution Principle</strong> states that <strong>objects of a derived class should be able to replace objects of the base class without affecting the correctness of the program</strong>. This principle ensures that inheritance hierarchies are correctly designed, promoting code reusability and maintainability.</p><h3>Bad Example</h3><pre>class Rectangle{<br>    int width;<br>    int height;<br>  <br>    Rectangle(int width, int height){<br>        this.width = width;<br>        this.height = height;<br>    }<br>    public void setWidth(int width) {<br>        this.width = width;<br>    }<br>    public void setHeight(int height) {<br>        this.height = height;<br>    }<br>    public int area(){<br>        return width * height;<br>    }<br>}<br>class  Square extends  Rectangle{<br>    Square(int side) {<br>        super(side, side);<br>    }<br>    @Override<br>    public void setHeight(int height) {<br>        super.setHeight(height);<br>        super.setWidth(height);<br>    }<br>    @Override<br>    public void setWidth(int width) {<br>        super.setWidth(width);<br>        super.setHeight(width);<br>    }<br>}<br>class Test {<br>    public static void main(String[] args) {<br>        Rectangle rectangle = new Square(10);<br>        rectangle.setWidth(5); // it will set both height and width as 5, which is not a rec behavior.<br>        System.out.println(rectangle.area());<br>    }<br>}</pre><p><strong>Violation of LSP</strong></p><p>In this example, setting the width or height of a <strong>Square</strong> object will change both dimensions, which is not the expected behavior for a <strong>Rectangle</strong>. This violates LSP because a <strong>Square</strong> cannot replace a <strong>Rectangle</strong> without affecting the program&#39;s correctness.</p><h3>Solution</h3><pre>interface Shape{<br>    int area();<br>}<br><br>class Rectangle implements   Shape{<br>    int width;<br>    int height;<br>    Rectangle(int width, int height){<br>        this.width = width;<br>        this.height = height;<br>    }<br>    public void setHeight(int height) {<br>        this.height = height;<br>    }<br>    public void setWidth(int width) {<br>        this.width = width;<br>    }<br>    @Override<br>    public int area() {<br>        return height * width;<br>    }<br>}<br>class  Square implements  Shape{<br>    int side;<br>    Square(int side){<br>        this.side = side;<br>    }<br>    public void setSide(int side) {<br>        this.side = side;<br>    }<br>    @Override<br>    public int area() {<br>        return side * side;<br>    }<br>}<br>class Test {<br>    public static void main(String[] args) {<br>        Shape shape = new Square(10);<br>        System.out.println(&quot;Square area = &quot; + shape.area());<br>        <br>        Shape shape1 = new Rectangle(10, 15);<br>        System.out.println(&quot;Rectangle Area: &quot; + shape1.area());<br>        <br>    }<br>}</pre><p>In this corrected version, both <strong>Rectangle</strong> and <strong>Square</strong> implement the <strong>Shape</strong> interface, allowing them to be used interchangeably without violating LSP.</p><p><strong>Benefits of LSP</strong></p><ul><li><strong>Robust Inheritance Hierarchies</strong>: Ensures that derived classes can replace base classes without affecting program correctness.</li><li><strong>Code Reusability</strong>: Promotes the creation of reusable code by ensuring that derived classes can be used in place of base classes.</li><li><strong>Maintainability</strong>: Helps in designing flexible systems that can accommodate changes without breaking existing functionality.</li></ul><h3>4. Interface Segregation Principle (ISP)</h3><p>The <strong>Interface Segregation Principle (ISP)</strong> states that <strong>no client should be forced to depend on methods it does not use</strong>. This principle encourages developers to create more focused and granular interfaces, ensuring that classes only implement what they actually need</p><h3>Bad Example</h3><pre>interface Worker {<br>    void work();<br>    void eat();<br>}<br>class HumanWorker implements Worker {<br>    @Override<br>    public void work() {/* Human working */;}<br>    @Override<br>    public void eat() {/* Human eating */;}<br>}<br>class RobotWorker implements Worker {<br>    @Override<br>     public void work() {/* Robot working */;}<br>    @Override<br>    public void eat() {<br>        // Robots don&#39;t eat, but must implement this method<br>        throw new UnsupportedOperationException(&quot;Robots cannot eat&quot;);<br>    }<br>}</pre><p><strong>Violation of ISP</strong></p><p>In this example, <strong>RobotWorker</strong> is forced to implement the <strong>eat()</strong> method, which it does not need.</p><h3>Solution</h3><pre>interface Workable {<br>    void work();<br>}<br>interface Eatable {<br>    void eat();<br>}<br>class RobotWorker implements Workable {<br>    @Override<br>    public void work() {/* Robot working */;}<br>}<br>class HumanWorker implements Workable, Eatable {<br>    @Override<br>    public void work() {/* Human working */;}<br>    @Override<br>    public void eat() {/* Human eating */;}<br>}</pre><p>Now, <strong>RobotWorker</strong> only implements the <strong>Workable</strong> interface, adhering to ISP.</p><p><strong>Benefits of ISP</strong></p><ul><li><strong>Decoupling</strong>: Reduces dependencies between classes.</li><li><strong>Flexibility</strong>: Allows different parts of the application to evolve independently.</li><li><strong>Maintainability</strong>: Simplifies maintenance by reducing unintended side effects when interfaces change.</li><li><strong>Code Readability</strong>: Smaller interfaces are easier to understand and implement</li></ul><h3>5. Dependency Inversion Principle (DIP)</h3><p>The <strong>Dependency Inversion Principle (DIP)</strong> states that <strong>depend upon interfaces or abstract functions and classes rather than upon concrete functions and classes.</strong> It means that the <strong>high-level module must not depend on the low-level module, but they should depend on abstractions.</strong></p><h3>Bad Example</h3><pre>class Macbook{<br>    private final WiredKeyboard keyboard;<br>    private final WiredMouse mouse;<br>    <br>    Macbook(){<br>        mouse = new WiredMouse(); // object of concrete class<br>        keyboard = new WiredKeyboard();<br>    }<br>}</pre><p><strong>Violation of DIP</strong></p><p>Now if we want to add <strong>bluetooth keyboard</strong> then we will not be able to because we have assigned object of concrete class</p><h3>Solution</h3><pre>interface Keyboard{ }<br>interface Mouse{ }<br><br>class Macbook{<br>    private final Keyboard keyboard;<br>    private final Mouse mouse;<br>    Macbook(Keyboard keyboard, Mouse mouse){<br>        this.keyboard = keyboard;<br>        this.mouse = mouse;<br>    }<br>}</pre><p>Now we are dependent on interface rather than depending on concrete classes.</p><p><strong>Benefits of DIP</strong></p><ul><li><strong>Modularity</strong>: Enhances the modularity of the system by reducing dependencies.</li><li><strong>Flexibility</strong>: Makes it easier to change or replace low-level modules without affecting high-level logic.</li><li><strong>Testability</strong>: Improves testability by allowing mock implementations of dependencies.</li></ul><h3>Thanks for Reading! 🙏</h3><p>If you found this article helpful, please give it a clap 👏 and share it with others who might benefit from it.</p><p>Follow me on <a href="https://www.linkedin.com/in/iamadityaraj04/">LinkedIn</a> and <a href="https://medium.com/@iamadityaraj04">Medium</a> for more insights on software development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ef5a3e8d402" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>