{"id":186,"date":"2024-02-01T05:47:18","date_gmt":"2024-02-01T05:47:18","guid":{"rendered":"https:\/\/hoclaptrinh.fun\/?p=186"},"modified":"2024-02-01T07:01:34","modified_gmt":"2024-02-01T07:01:34","slug":"mastering-design-principles-solid","status":"publish","type":"post","link":"https:\/\/hoclaptrinh.fun\/index.php\/2024\/02\/01\/mastering-design-principles-solid\/","title":{"rendered":"Mastering Design Principles &#8211; SOLID"},"content":{"rendered":"\n\t<div id=\"text-3079651271\" class=\"text\">\n\t\t\n\n<p>In the fast-paced world of software development, writing\u00a0<em>robust<\/em>,\u00a0<em>maintainable<\/em>, and\u00a0<em>scalable<\/em>\u00a0code is critically important. One way to achieve this is by following a set of fundamental design principles known as the SOLID principles. These principles provide a clear framework for crafting software that is easy to understand, extend, and maintain.\u00a0<\/p>\n<p>In this newsletter, we will explore the SOLID principles, examining each component in detail. We will review practical implementation guidance and best practices for applying them.<\/p>\n<p>Now, let&#8217;s begin our exploration with a brief overview of the SOLID principles first.<\/p>\n<h2 class=\"header-with-anchor-widget\">A Brief Overview<\/h2>\n<p>The SOLID principles are a set of five fundamental design principles that were introduced by Robert C. Martin to guide software developers in creating maintainable, scalable, and flexible software systems. These principles, when followed, contribute to the development of software that is easier to understand, modify, and extend over time.\u00a0<\/p>\n<p>The SOLID acronym stands for:<\/p>\n<div class=\"captioned-image-container\">\n<figure>\n<div class=\"image2-inset\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-large wp-image-188\" src=\"https:\/\/hoclaptrinh.fun\/wp-content\/uploads\/2024\/02\/2db4d634-e08c-4ced-8ca8-dbea85f6afe4_3827x3184-1024x852.png\" alt=\"\" width=\"1020\" height=\"849\" srcset=\"https:\/\/hoclaptrinh.fun\/wp-content\/uploads\/2024\/02\/2db4d634-e08c-4ced-8ca8-dbea85f6afe4_3827x3184-1024x852.png 1024w, https:\/\/hoclaptrinh.fun\/wp-content\/uploads\/2024\/02\/2db4d634-e08c-4ced-8ca8-dbea85f6afe4_3827x3184-300x250.png 300w, https:\/\/hoclaptrinh.fun\/wp-content\/uploads\/2024\/02\/2db4d634-e08c-4ced-8ca8-dbea85f6afe4_3827x3184-768x639.png 768w, https:\/\/hoclaptrinh.fun\/wp-content\/uploads\/2024\/02\/2db4d634-e08c-4ced-8ca8-dbea85f6afe4_3827x3184-1536x1278.png 1536w, https:\/\/hoclaptrinh.fun\/wp-content\/uploads\/2024\/02\/2db4d634-e08c-4ced-8ca8-dbea85f6afe4_3827x3184-2048x1704.png 2048w, https:\/\/hoclaptrinh.fun\/wp-content\/uploads\/2024\/02\/2db4d634-e08c-4ced-8ca8-dbea85f6afe4_3827x3184-510x424.png 510w\" sizes=\"(max-width: 1020px) 100vw, 1020px\" \/><\/p>\n<div class=\"image-link-expand\">\u00a0<\/div>\n<\/div>\n<\/figure>\n<\/div>\n<h2 class=\"header-with-anchor-widget\">Importance of Design Principles in Software Development<\/h2>\n<div id=\"\u00a7importance-of-design-principles-in-software-development\" class=\"header-anchor-widget offset-top\">\n<div class=\"header-anchor-widget-button-container\">\n<div class=\"header-anchor-widget-button\">\u00a0<\/div>\n<\/div>\n<\/div>\n<p>Design principles, such as the SOLID principles, play a pivotal role in the software development process for several reasons:<\/p>\n<ul>\n<li>\n<p><strong>Maintainability:<\/strong>\u00a0Following sound design principles makes code more maintainable. When code is well-structured and adheres to these principles, it becomes easier to identify and fix issues, add new features, and make improvements without causing unintended consequences.<\/p>\n<\/li>\n<li>\n<p><strong>Scalability:<\/strong>\u00a0Well-designed software is scalable. It can accommodate changes and growth in requirements without requiring extensive rework or becoming increasingly complex.<\/p>\n<\/li>\n<li>\n<p><strong>Code Reusability:<\/strong>\u00a0Adhering to design principles often leads to code that is more reusable. Reusable components save time and effort in development and testing.<\/p>\n<\/li>\n<li>\n<p><strong>Collaboration:<\/strong>\u00a0Design principles provide a common framework for developers to work within. This common understanding promotes collaboration and reduces misunderstandings among team members.<\/p>\n<\/li>\n<li>\n<p><strong>Reduced Bugs and Pitfalls:<\/strong>\u00a0Following design principles helps to identify and mitigate common programming pitfalls and design flaws. This results in fewer bugs and more robust software.<\/p>\n<\/li>\n<li>\n<p><strong>Future-Proofing:\u00a0<\/strong>Well-designed software can adapt to changing requirements and technologies. It&#8217;s an investment in the long-term viability of the software product.<\/p>\n<\/li>\n<\/ul>\n<p>Now, let&#8217;s deep dive into each component of the SOLID principles.<\/p>\n<h1 class=\"header-with-anchor-widget\"><strong>Single Responsibility Principle (SRP)<\/strong><\/h1>\n<div id=\"\u00a7single-responsibility-principle-srp\" class=\"header-anchor-widget offset-top\">\n<div class=\"header-anchor-widget-button-container\">\n<div class=\"header-anchor-widget-button\">\u00a0<\/div>\n<\/div>\n<\/div>\n<p>The \u201cS\u201d in the SOLID principles stands for the\u00a0<strong>Single Responsibility Principle (SRP)<\/strong>, which states that a class should have only one reason to change or, in other words, it should have a single, well-defined responsibility or job within a software system.<\/p>\n<h2 class=\"header-with-anchor-widget\">Illustrating a Violation of SRP<\/h2>\n<p>Let&#8217;s take a look at a Java code example below that clearly violates the Single Responsibility Principle (SRP) principle:<\/p>\n<pre><code>public class Employee {\n\u00a0 \u00a0 private String name;\n\u00a0 \u00a0 private double salary;\n\n\u00a0 \u00a0 public void calculateSalary() {\n\u00a0 \u00a0 \u00a0 \u00a0 \/\/ definition\n\u00a0 \u00a0 }\n\u00a0 \u00a0 public void generatePayrollReport() {\n\u00a0 \u00a0 \u00a0 \u00a0 \/\/ definition\n\u00a0 \u00a0 }\n}<\/code><\/pre>\n<p>In the above example, the Employee class has two responsibilities: calculating an employee&#8217;s salary and generating a payroll report. This violates the SRP because it has more than one reason to change.<\/p>\n<h2 class=\"header-with-anchor-widget\">Fixing the Violation (SRP)<\/h2>\n<p>To address the violation of the Single Responsibility Principle (SRP) in our previous example, let&#8217;s refactor the code to separate concerns and ensure that each class has a single, well-defined responsibility. We&#8217;ll create distinct classes for calculating an employee&#8217;s salary and generating a payroll report:<\/p>\n<pre><code>public class Employee {\n\u00a0 \u00a0 private String name;\n\u00a0 \u00a0 private double salary;\n\n\u00a0 \u00a0 public void calculateSalary() {\n\u00a0 \u00a0 \u00a0 \u00a0 \/\/ definition\n\u00a0 \u00a0 }\n}\n\npublic class PayrollReportGenerator {\n\u00a0 \u00a0 public void generatePayrollReport(Employee employee) {\n\u00a0 \u00a0 \u00a0 \u00a0 \/\/ definition\n\u00a0 \u00a0 }\n}<\/code><\/pre>\n<p>In the refactored solution, the responsibilities of calculating the salary and generating a payroll report have been separated into two distinct classes (Employee and PayrollReportGenerator), each with a single responsibility. This adheres to the SRP.<\/p>\n<p>Let\u2019s take a look at the visual representation of the classes and implementation of the single responsibility principle (SRP).<\/p>\n<div class=\"captioned-image-container\">\n<figure>\n<div class=\"image2-inset\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-large wp-image-191\" src=\"https:\/\/hoclaptrinh.fun\/wp-content\/uploads\/2024\/02\/d898df3b-5612-474b-a022-cc6a0d926516_3900x2953-1024x775.png\" alt=\"\" width=\"1020\" height=\"772\" srcset=\"https:\/\/hoclaptrinh.fun\/wp-content\/uploads\/2024\/02\/d898df3b-5612-474b-a022-cc6a0d926516_3900x2953-1024x775.png 1024w, https:\/\/hoclaptrinh.fun\/wp-content\/uploads\/2024\/02\/d898df3b-5612-474b-a022-cc6a0d926516_3900x2953-300x227.png 300w, https:\/\/hoclaptrinh.fun\/wp-content\/uploads\/2024\/02\/d898df3b-5612-474b-a022-cc6a0d926516_3900x2953-768x582.png 768w, https:\/\/hoclaptrinh.fun\/wp-content\/uploads\/2024\/02\/d898df3b-5612-474b-a022-cc6a0d926516_3900x2953-1536x1163.png 1536w, https:\/\/hoclaptrinh.fun\/wp-content\/uploads\/2024\/02\/d898df3b-5612-474b-a022-cc6a0d926516_3900x2953-2048x1551.png 2048w, https:\/\/hoclaptrinh.fun\/wp-content\/uploads\/2024\/02\/d898df3b-5612-474b-a022-cc6a0d926516_3900x2953-510x386.png 510w\" sizes=\"(max-width: 1020px) 100vw, 1020px\" \/><\/p>\n<div class=\"image-link-expand\">\u00a0<\/div>\n<\/div>\n<\/figure>\n<\/div>\n<h2 class=\"header-with-anchor-widget\">Pitfalls and Common Mistakes<\/h2>\n<p>Navigating the application of the Single Responsibility Principle (SRP) comes with common pitfalls and mistakes we should recognize. Understanding these challenges allow us to better avoid them and create more robust, maintainable code. Let&#8217;s explore some of these potential issues:<\/p>\n<ul>\n<li>\n<p>It is a common mistake to overload classes with multiple responsibilities, as demonstrated in the initial example. This can lead to complex and difficult-to-maintain code.<\/p>\n<\/li>\n<li>\n<p>Ignoring the principle of cohesion, which is related to SRP, can result in classes that perform unrelated tasks, making the code less organized and harder to manage.<\/p>\n<\/li>\n<\/ul>\n<h2 class=\"header-with-anchor-widget\">Best Practice Guidelines<\/h2>\n<p>To adhere to the Single Responsibility Principle effectively, consider the following guidelines:<\/p>\n<ul>\n<li>\n<p>Clearly define the responsibilities or roles that each class should have. Avoid mixing unrelated tasks within a single class.<\/p>\n<\/li>\n<li>\n<p>Use the Separation of Concerns (SoC) principle to divide your application&#8217;s functionality into distinct modules or classes, each responsible for a specific concern.<\/p>\n<\/li>\n<li>\n<p>If you find a class with multiple responsibilities, refactor it into smaller, more focused classes, each with a single responsibility.<\/p>\n<\/li>\n<li>\n<p>Design your classes in a way that changes to one responsibility do not affect the implementation of other responsibilities.<\/p>\n<\/li>\n<li>\n<p>Conduct code reviews to ensure that classes adhere to SRP. Encourage team members to provide feedback on class responsibilities.<\/p>\n<\/li>\n<\/ul>\n<h1 class=\"header-with-anchor-widget\"><strong>Open\/Closed Principle (OCP)<\/strong><\/h1>\n<p>The<strong>\u00a0Open\/Closed Principle (OCP)<\/strong>\u00a0states that software entities (such as classes, modules, and functions) should be open for extension but closed for modification. In other words, you should be able to add new functionality or behavior to a software entity without altering its existing source code.<\/p>\n<h2 class=\"header-with-anchor-widget\">Illustrating a Violation of OCP<\/h2>\n<p>To understand the Open\/Closed Principle (OCP) better, let&#8217;s take a look at a Java code example that clearly violates this principle:<\/p>\n<pre><code>public class Rectangle {\n\u00a0 \u00a0 protected int width;\n\u00a0 \u00a0 protected int height;\n\n\u00a0 \u00a0 public Rectangle(int width, int height) {\n\u00a0 \u00a0 \u00a0 \u00a0 this.width = width;\n\u00a0 \u00a0 \u00a0 \u00a0 this.height = height;\n\u00a0 \u00a0 }\n\u00a0\n\u00a0 \u00a0 public int getWidth() {\n\u00a0 \u00a0 \u00a0 \u00a0 return width;\n\u00a0 \u00a0 }\n\n\u00a0 \u00a0 public void setWidth(int width) {\n\u00a0 \u00a0 \u00a0 \u00a0 this.width = width;\n\u00a0 \u00a0 }\n\n\u00a0 \u00a0 public int getHeight() {\n\u00a0 \u00a0 \u00a0 \u00a0 return height;\n\u00a0 \u00a0 }\n \n  \u00a0 public void setHeight(int height) {\n\u00a0 \u00a0 \u00a0 \u00a0 this.height = height;\n\u00a0 \u00a0 }\u00a0 \u00a0 \u00a0 \u00a0 \n\n    public int calculateArea() {\n\u00a0 \u00a0 \u00a0 \u00a0 return width * height;\n\u00a0 \u00a0 }\n}<\/code><\/pre>\n<p>In the above example, the Rectangle class is designed to calculate the area of a rectangle. However, if you want to extend it to work with other shapes like circles or triangles, you would need to modify the class, violating the OCP.<\/p>\n<h2 class=\"header-with-anchor-widget\">Fixing the Violation (OCP)<\/h2>\n<p>We&#8217;ll apply the OCP (Open-Closed Principle) and see how we can solve the issue mentioned above:<\/p>\n<pre><code>public abstract class Shape {\n\u00a0 \u00a0 public abstract int calculateArea();\n}\npublic class Rectangle extends Shape {\n\u00a0 \u00a0 private int width;\n\u00a0 \u00a0 private int height;\n\n\u00a0 \u00a0 public Rectangle(int width, int height) {\n\u00a0 \u00a0 \u00a0 \u00a0 this.width = width;\n\u00a0 \u00a0 \u00a0 \u00a0 this.height = height;\n\u00a0 \u00a0 }\n\n\u00a0 \u00a0 @Override\n\u00a0 \u00a0 public int calculateArea() {\n\u00a0 \u00a0 \u00a0 \u00a0 return width * height;\n\u00a0 \u00a0 }\n}\n\npublic class Circle extends Shape {\n\u00a0 \u00a0 private int radius;\n\n\u00a0 \u00a0 public Circle(int radius) {\n\u00a0 \u00a0 \u00a0 \u00a0 this.radius = radius;\n\u00a0 \u00a0 }\n\n\u00a0 \u00a0 @Override\n\u00a0 \u00a0 public int calculateArea() {\n\u00a0 \u00a0 \u00a0 \u00a0 return (int) (Math.PI * radius * radius);\n\u00a0 \u00a0 }\n}<\/code><\/pre>\n<p>In this refactored solution, the Shape class is introduced as an abstract base class for all shapes. Each specific shape (Rectangle, Circle) extends the Shape class and provides its implementation of the calculateArea method. This adheres to the OCP because you can add new shapes without modifying existing code.<\/p>\n<p>Below is the visual representation of the classes and implementation of OCP.<\/p>\n<div class=\"captioned-image-container\">\n<figure>\n<div class=\"image2-inset\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-large wp-image-193\" src=\"https:\/\/hoclaptrinh.fun\/wp-content\/uploads\/2024\/02\/edaa7d68-fc0e-47e8-ae77-ca6b17cfac6a_4639x2900-1024x640.png\" alt=\"\" width=\"1020\" height=\"638\" srcset=\"https:\/\/hoclaptrinh.fun\/wp-content\/uploads\/2024\/02\/edaa7d68-fc0e-47e8-ae77-ca6b17cfac6a_4639x2900-1024x640.png 1024w, https:\/\/hoclaptrinh.fun\/wp-content\/uploads\/2024\/02\/edaa7d68-fc0e-47e8-ae77-ca6b17cfac6a_4639x2900-300x188.png 300w, https:\/\/hoclaptrinh.fun\/wp-content\/uploads\/2024\/02\/edaa7d68-fc0e-47e8-ae77-ca6b17cfac6a_4639x2900-768x480.png 768w, https:\/\/hoclaptrinh.fun\/wp-content\/uploads\/2024\/02\/edaa7d68-fc0e-47e8-ae77-ca6b17cfac6a_4639x2900-1536x960.png 1536w, https:\/\/hoclaptrinh.fun\/wp-content\/uploads\/2024\/02\/edaa7d68-fc0e-47e8-ae77-ca6b17cfac6a_4639x2900-2048x1280.png 2048w, https:\/\/hoclaptrinh.fun\/wp-content\/uploads\/2024\/02\/edaa7d68-fc0e-47e8-ae77-ca6b17cfac6a_4639x2900-510x319.png 510w\" sizes=\"(max-width: 1020px) 100vw, 1020px\" \/><\/p>\n<div class=\"image-link-expand\">\u00a0<\/div>\n<\/div>\n<\/figure>\n<\/div>\n<h2 class=\"header-with-anchor-widget\">Pitfalls and Common Mistakes<\/h2>\n<div id=\"\u00a7pitfalls-and-common-mistakes\" class=\"header-anchor-widget offset-top\">\n<div class=\"header-anchor-widget-button-container\">\n<div class=\"header-anchor-widget-button\">\u00a0<\/div>\n<\/div>\n<\/div>\n<p>Let&#8217;s examine some of the common pitfalls and mistakes that developers may encounter:\u00a0<\/p>\n<ul>\n<li>\n<p>A common mistake is directly modifying existing code to add new functionality instead of extending it. This violates the OCP and can introduce bugs or regressions.<\/p>\n<\/li>\n<li>\n<p>Failing to introduce appropriate abstractions or base classes can lead to code that is hard to extend without modification.<\/p>\n<\/li>\n<\/ul>\n<h2 class=\"header-with-anchor-widget\">Best Practice Guidelines<\/h2>\n<p>To implement the Open\/Closed Principle effectively, consider the following guidelines:<\/p>\n<ul>\n<li>\n<p>Introduce abstract classes or interfaces to create abstractions that software entities can extend or implement to provide new functionality.<\/p>\n<\/li>\n<li>\n<p>When extending an abstract class or implementing an interface, override methods to provide specific behavior for each entity.<\/p>\n<\/li>\n<li>\n<p>Use polymorphism to treat objects of different concrete classes (e.g., different shapes) uniformly through their common base class or interface.<\/p>\n<\/li>\n<li>\n<p>Use dependency injection to inject dependencies or behaviors into classes rather than hardcoding them, making it easier to extend functionality.<\/p>\n<\/li>\n<\/ul>\n<h1 class=\"header-with-anchor-widget\"><strong>Liskov Substitution Principle (LSP)<\/strong><\/h1>\n<p>The\u00a0<strong>Liskov Substitution Principle (LSP)<\/strong>\u00a0states that objects of a derived class (subtype) should be able to replace objects of the base class (supertype) without affecting the correctness of the program. In other words, if class A is a subtype of class B, then instances of class B should be replaceable with instances of class A without causing issues.<\/p>\n<h2 class=\"header-with-anchor-widget\">Illustrating a Violation of LSP<\/h2>\n<p>To understand the Liskov Substitution Principle (LSP) better, let&#8217;s take a look at a Java code example that clearly violates this principle:<\/p>\n<pre><code>class Bird {\n\u00a0 \u00a0 void fly() {\n\u00a0 \u00a0 \u00a0 \u00a0 System.out.println(\"A bird can fly.\");\n\u00a0 \u00a0 }\n}\n\nclass Ostrich extends Bird {\n\u00a0 \u00a0 @Override\n\u00a0 \u00a0 void fly() {\n\u00a0 \u00a0 \u00a0 \u00a0 \/\/ Ostriches cannot fly, so this method is overridden to do nothing.\n\u00a0 \u00a0 }\n}<\/code><\/pre>\n<p>In this example, the Ostrich class is a subtype of the Bird class. However, it violates the LSP because it overrides the fly method which is not related to Ostrich. This means that an instance of Ostrich cannot be substituted for an instance of Bird without causing unexpected behavior.<\/p>\n<h2 class=\"header-with-anchor-widget\">Fixing the Violation (LSP)<\/h2>\n<p>We&#8217;ll apply the Liskov Substitution Principle (LSP) and see how we can solve the issue mentioned above:<\/p>\n<pre><code>class Bird {\n\u00a0 \u00a0 void move() {\n\u00a0 \u00a0 \u00a0 \u00a0 System.out.println(\"A bird can move.\");\n\u00a0 \u00a0 }\n}\n\nclass Ostrich extends Bird {\n\u00a0 \u00a0 @Override\n\u00a0 \u00a0 void move() {\n\u00a0 \u00a0 \u00a0 \u00a0 System.out.println(\"An Ostrich can move.\");\n\u00a0 \u00a0 }\n}<\/code><\/pre>\n<p>In this revised example, the Ostrich class is a subtype of the Bird class, and it overrides the move method to provide a meaningful behavior that aligns with the LSP. An instance of Ostrich can be substituted for an instance of Bird without causing issues.<\/p>\n<p>Here is the visual representation of the classes and implementation of LSP.<\/p>\n<div class=\"captioned-image-container\">\n<figure>\n<div class=\"image2-inset\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-large wp-image-189\" src=\"https:\/\/hoclaptrinh.fun\/wp-content\/uploads\/2024\/02\/84024ff6-c425-41cc-810a-8f5196fa81e8_4639x2938-1024x649.png\" alt=\"\" width=\"1020\" height=\"646\" srcset=\"https:\/\/hoclaptrinh.fun\/wp-content\/uploads\/2024\/02\/84024ff6-c425-41cc-810a-8f5196fa81e8_4639x2938-1024x649.png 1024w, https:\/\/hoclaptrinh.fun\/wp-content\/uploads\/2024\/02\/84024ff6-c425-41cc-810a-8f5196fa81e8_4639x2938-300x190.png 300w, https:\/\/hoclaptrinh.fun\/wp-content\/uploads\/2024\/02\/84024ff6-c425-41cc-810a-8f5196fa81e8_4639x2938-768x486.png 768w, https:\/\/hoclaptrinh.fun\/wp-content\/uploads\/2024\/02\/84024ff6-c425-41cc-810a-8f5196fa81e8_4639x2938-1536x973.png 1536w, https:\/\/hoclaptrinh.fun\/wp-content\/uploads\/2024\/02\/84024ff6-c425-41cc-810a-8f5196fa81e8_4639x2938-2048x1297.png 2048w, https:\/\/hoclaptrinh.fun\/wp-content\/uploads\/2024\/02\/84024ff6-c425-41cc-810a-8f5196fa81e8_4639x2938-510x323.png 510w\" sizes=\"(max-width: 1020px) 100vw, 1020px\" \/><\/p>\n<div class=\"image-link-expand\">\u00a0<\/div>\n<\/div>\n<\/figure>\n<\/div>\n<h2 class=\"header-with-anchor-widget\">Pitfalls and Common Mistakes<\/h2>\n<p>As we learn how to apply the Liskov Substitution Principle (LSP), it&#8217;s essential to be aware of common pitfalls and mistakes that developers may encounter. Let&#8217;s explore some of these potential issues:<\/p>\n<ul>\n<li>\n<p>A common mistake is overriding methods in derived classes in a way that contradicts the behavior of the base class.<\/p>\n<\/li>\n<li>\n<p>Changing the preconditions (input requirements) or postconditions (output guarantees) of methods in derived classes can violate LSP.<\/p>\n<\/li>\n<\/ul>\n<h2 class=\"header-with-anchor-widget\">Best Practice Guidelines<\/h2>\n<p>To implement the Liskov Substitution Principle effectively, consider the following guidelines:<\/p>\n<ul>\n<li>\n<p>Ensure that derived classes maintain the behavioral compatibility of their base classes. Methods in derived classes should follow the same contracts as the base class methods.<\/p>\n<\/li>\n<li>\n<p>If a base class method has specific preconditions (e.g., input constraints), derived class methods should have the same or weaker preconditions. Postconditions (output guarantees) should be as strong as or stronger than those of the base class methods.<\/p>\n<\/li>\n<li>\n<p>Use polymorphism to enable the substitution of derived class objects for base class objects. This often involves overriding methods to provide specialized behavior while maintaining the core functionality.<\/p>\n<\/li>\n<\/ul>\n<h1 class=\"header-with-anchor-widget\"><strong>Interface Segregation Principle (ISP)<\/strong><\/h1>\n<p>The \u201cI\u201d in the SOLID acronym stands for the\u00a0<strong>Interface Segregation Principle (ISP)<\/strong>\u00a0which emphasizes that clients (classes or components that use interfaces) should not be forced to depend on interfaces they don&#8217;t use. In other words, an interface should have a specific and focused set of methods that are relevant to the implementing classes.<\/p>\n<h2 class=\"header-with-anchor-widget\">Illustrating a Violation of ISP<\/h2>\n<p>Let&#8217;s check out a Java code example that clearly violates this principle:<\/p>\n<pre><code>\/\/ Monolithic interface\ninterface Worker {\n\u00a0 \u00a0 void work();\n\u00a0 \u00a0 void eat();\n\u00a0 \u00a0 void sleep();\n}<\/code><\/pre>\n<p>In this example, the Worker interface contains three methods: work(), eat(), and sleep(). However, not all classes that implement this interface may need all these methods. This can lead to classes being forced to implement methods that are irrelevant to their functionality, violating the ISP.<\/p>\n<h2 class=\"header-with-anchor-widget\">Fixing the Violation (ISP)<\/h2>\n<p>We&#8217;ll apply the Interface Segregation Principle (ISP) and see how we can solve the issue mentioned above:<\/p>\n<pre><code>interface Workable {\n\u00a0 \u00a0 void work();\n}\n\ninterface Eatable {\n\u00a0 \u00a0 void eat();\n}\n\ninterface Sleepable {\n\u00a0 \u00a0 void sleep();\n}<\/code><\/pre>\n<p>In this refactored solution, the Worker interface has been split into three smaller, more focused interfaces: Workable, Eatable, and Sleepable. Now, classes can choose to implement only the interfaces that are relevant to their functionality, adhering to the ISP.<\/p>\n<p>A visual representation of the refactored interfaces (Workable, Eatable, Sleepable) adhering the ISP is shown below.<\/p>\n<div class=\"captioned-image-container\">\n<figure>\n<div class=\"image2-inset\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-large wp-image-192\" src=\"https:\/\/hoclaptrinh.fun\/wp-content\/uploads\/2024\/02\/dcb8bc03-d127-4e68-929f-d9bfd3f5cdf6_6140x3000-1024x500.png\" alt=\"\" width=\"1020\" height=\"498\" srcset=\"https:\/\/hoclaptrinh.fun\/wp-content\/uploads\/2024\/02\/dcb8bc03-d127-4e68-929f-d9bfd3f5cdf6_6140x3000-1024x500.png 1024w, https:\/\/hoclaptrinh.fun\/wp-content\/uploads\/2024\/02\/dcb8bc03-d127-4e68-929f-d9bfd3f5cdf6_6140x3000-300x147.png 300w, https:\/\/hoclaptrinh.fun\/wp-content\/uploads\/2024\/02\/dcb8bc03-d127-4e68-929f-d9bfd3f5cdf6_6140x3000-768x375.png 768w, https:\/\/hoclaptrinh.fun\/wp-content\/uploads\/2024\/02\/dcb8bc03-d127-4e68-929f-d9bfd3f5cdf6_6140x3000-1536x750.png 1536w, https:\/\/hoclaptrinh.fun\/wp-content\/uploads\/2024\/02\/dcb8bc03-d127-4e68-929f-d9bfd3f5cdf6_6140x3000-2048x1001.png 2048w, https:\/\/hoclaptrinh.fun\/wp-content\/uploads\/2024\/02\/dcb8bc03-d127-4e68-929f-d9bfd3f5cdf6_6140x3000-510x249.png 510w\" sizes=\"(max-width: 1020px) 100vw, 1020px\" \/><\/p>\n<div class=\"image-link-expand\">\u00a0<\/div>\n<\/div>\n<\/figure>\n<\/div>\n<h2 class=\"header-with-anchor-widget\">Pitfalls and Common Mistakes<\/h2>\n<p>Let&#8217;s examine some of the common pitfalls and mistakes that developers may encounter while applying ISP:<\/p>\n<ul>\n<li>\n<p>Creating large, monolithic interfaces with too many methods can lead to classes implementing methods they don&#8217;t need, violating ISP.<\/p>\n<\/li>\n<li>\n<p>Modifying an interface to add or remove methods can break existing implementations. It&#8217;s important to consider the impact on clients when making changes.<\/p>\n<\/li>\n<\/ul>\n<h2 class=\"header-with-anchor-widget\">Best Practice Guidelines<\/h2>\n<p>To adhere to the Interface Segregation Principle effectively, consider the following guidelines:<\/p>\n<ul>\n<li>\n<p>Design interfaces with a specific purpose, containing only methods that are directly related to that purpose.<\/p>\n<\/li>\n<li>\n<p>Prefer having multiple smaller interfaces that clients can choose to implement rather than a single large interface with everything.<\/p>\n<\/li>\n<li>\n<p>Think from the perspective of the clients (classes that implement the interface) and provide them with interfaces that are tailored to their needs.<\/p>\n<\/li>\n<li>\n<p>If you need to add new methods to an existing interface without breaking existing implementations, consider using default methods, which provide default implementations for new methods.<\/p>\n<\/li>\n<\/ul>\n<h1 class=\"header-with-anchor-widget\"><strong>Dependency Inversion Principle (DIP)<\/strong><\/h1>\n<p>The\u00a0<strong>Dependency Inversion Principle (DIP)<\/strong>\u00a0states that high-level modules (or classes) should not depend on low-level modules; both should depend on abstractions (interfaces or abstract classes). In simpler terms, the principle encourages the use of abstract interfaces to decouple higher-level components from lower-level details.<\/p>\n<h2 class=\"header-with-anchor-widget\">Illustrating a Violation of DIP<\/h2>\n<p>To understand the Dependency Inversion Principle (DIP) better, let&#8217;s take a look at a Java code example that clearly violates this principle:<\/p>\n<pre><code>class LightBulb {\n\u00a0 \u00a0 void turnOn() {\n\u00a0 \u00a0 \u00a0 \u00a0 \/\/ Code to turn on the light bulb.\n\u00a0 \u00a0 }\n}\n\nclass Switch {\n\u00a0 \u00a0 private LightBulb bulb;\n\n\u00a0 \u00a0 Switch(LightBulb bulb) {\n\u00a0 \u00a0 \u00a0 \u00a0 this.bulb = bulb;\n\u00a0 \u00a0 }\n\n\u00a0 \u00a0 void operate() {\n\u00a0 \u00a0 \u00a0 \u00a0 bulb.turnOn();\n\u00a0 \u00a0 }\n}<\/code><\/pre>\n<p>In this example, the Switch class directly depends on the LightBulb class, which is a lower-level detail. This is a violation of the DIP because high-level modules like Switch should not depend on low-level details.<\/p>\n<h2 class=\"header-with-anchor-widget\">Fixing the Violation (DIP)<\/h2>\n<p>We&#8217;ll apply the Dependency Inversion Principle (DIP) and see how we can solve the issue mentioned above:<\/p>\n<pre><code>interface Switchable {\n\u00a0 \u00a0 void turnOn();\n}\n\nclass LightBulb implements Switchable {\n\u00a0 \u00a0 @Override\n\u00a0 \u00a0 public void turnOn() {\n\u00a0 \u00a0 \u00a0 \u00a0 \/\/ Code to turn on the light bulb.\n\u00a0 \u00a0 }\n}\n\nclass Switch {\n\u00a0 \u00a0 private Switchable device;\n\n\u00a0 \u00a0 Switch(Switchable device) {\n\u00a0 \u00a0 \u00a0 \u00a0 this.device = device;\n\u00a0 \u00a0 }\n\n\u00a0 \u00a0 void operate() {\n\u00a0 \u00a0 \u00a0 \u00a0 device.turnOn();\n\u00a0 \u00a0 }\n}<\/code><\/pre>\n<p>In this refactored solution, the Switch class depends on the Switchable interface, which is an abstraction. The LightBulb class implements the Switchable interface. This adheres to the DIP because high-level modules now depend on abstractions rather than low-level details.<\/p>\n<p>A visual representation of the dependency inversion, showing how high-level modules (Switch) depend on abstractions (Switchable) rather than concrete implementations (LightBulb) is shown below.<\/p>\n<div class=\"captioned-image-container\">\n<figure>\n<div class=\"image2-inset\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-large wp-image-190\" src=\"https:\/\/hoclaptrinh.fun\/wp-content\/uploads\/2024\/02\/cc847fc7-3a48-48d0-905b-c07c7b49b62f_5977x2896-1024x496.png\" alt=\"\" width=\"1020\" height=\"494\" srcset=\"https:\/\/hoclaptrinh.fun\/wp-content\/uploads\/2024\/02\/cc847fc7-3a48-48d0-905b-c07c7b49b62f_5977x2896-1024x496.png 1024w, https:\/\/hoclaptrinh.fun\/wp-content\/uploads\/2024\/02\/cc847fc7-3a48-48d0-905b-c07c7b49b62f_5977x2896-300x145.png 300w, https:\/\/hoclaptrinh.fun\/wp-content\/uploads\/2024\/02\/cc847fc7-3a48-48d0-905b-c07c7b49b62f_5977x2896-768x372.png 768w, https:\/\/hoclaptrinh.fun\/wp-content\/uploads\/2024\/02\/cc847fc7-3a48-48d0-905b-c07c7b49b62f_5977x2896-1536x744.png 1536w, https:\/\/hoclaptrinh.fun\/wp-content\/uploads\/2024\/02\/cc847fc7-3a48-48d0-905b-c07c7b49b62f_5977x2896-2048x992.png 2048w, https:\/\/hoclaptrinh.fun\/wp-content\/uploads\/2024\/02\/cc847fc7-3a48-48d0-905b-c07c7b49b62f_5977x2896-510x247.png 510w\" sizes=\"(max-width: 1020px) 100vw, 1020px\" \/><\/p>\n<div class=\"image-link-expand\">\u00a0<\/div>\n<\/div>\n<\/figure>\n<\/div>\n<h2 class=\"header-with-anchor-widget\">Pitfalls and Common Mistakes<\/h2>\n<div id=\"\u00a7pitfalls-and-common-mistakes\" class=\"header-anchor-widget offset-top\">\n<div class=\"header-anchor-widget-button-container\">\n<div class=\"header-anchor-widget-button\">\u00a0<\/div>\n<\/div>\n<\/div>\n<p>Let\u2019s examine some of the pitfalls and common mistakes as we learn to apply the Dependency Inversion Principle (DIP):<\/p>\n<ul>\n<li>\n<p>A common mistake is having high-level modules directly depend on low-level details, violating the DIP.<\/p>\n<\/li>\n<li>\n<p>Creating weak or poorly defined abstractions can make it challenging to adhere to the DIP effectively.<\/p>\n<\/li>\n<\/ul>\n<h2 class=\"header-with-anchor-widget\">Best Practice Guidelines<\/h2>\n<p>To implement the Dependency Inversion Principle effectively, consider the following guidelines:<\/p>\n<ul>\n<li>\n<p>Introduce abstract interfaces or abstract classes to represent dependencies, allowing high-level modules to depend on these abstractions.<\/p>\n<\/li>\n<li>\n<p>Use dependency injection to inject concrete implementations into high-level modules through their abstractions. This promotes loose coupling.<\/p>\n<\/li>\n<li>\n<p>Combining DIP with other SOLID principles can lead to cleaner and more maintainable code.<\/p>\n<\/li>\n<li>\n<p>Consider using dependency injection frameworks like Spring or Guice to manage dependencies automatically.<\/p>\n<\/li>\n<\/ul>\n<h1 class=\"header-with-anchor-widget\"><strong>Concluding Remarks<\/strong><\/h1>\n<p>The SOLID principles are essential guidelines for designing and maintaining high-quality, flexible, and robust software systems. Encouraging the application of these principles in software development practices can lead to more efficient development, fewer bugs, and a smoother evolution of software products over time. Embracing SOLID principles is an investment in the long-term success and sustainability of software projects.<\/p>\n<h2 class=\"header-with-anchor-widget\">Reading Material<\/h2>\n<ul>\n<li>\n<p><em>\u2018Clean Code: A Handbook of Agile Software Craftsmanship\u2019<\/em>\u00a0by Robert C. Martin<\/p>\n<\/li>\n<li>\n<p><em>\u2018Design Patterns: Elements of Reusable Object-Oriented Software\u2019<\/em>\u00a0by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides.<\/p>\n<\/li>\n<\/ul>\n\t\t\n<style>\n#text-3079651271 {\n  font-size: 1.2rem;\n}\n<\/style>\n\t<\/div>\n\t\n\n","protected":false},"excerpt":{"rendered":"","protected":false},"author":1,"featured_media":188,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[30],"class_list":["post-186","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-blog","tag-solid"],"_links":{"self":[{"href":"https:\/\/hoclaptrinh.fun\/index.php\/wp-json\/wp\/v2\/posts\/186"}],"collection":[{"href":"https:\/\/hoclaptrinh.fun\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/hoclaptrinh.fun\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/hoclaptrinh.fun\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/hoclaptrinh.fun\/index.php\/wp-json\/wp\/v2\/comments?post=186"}],"version-history":[{"count":4,"href":"https:\/\/hoclaptrinh.fun\/index.php\/wp-json\/wp\/v2\/posts\/186\/revisions"}],"predecessor-version":[{"id":196,"href":"https:\/\/hoclaptrinh.fun\/index.php\/wp-json\/wp\/v2\/posts\/186\/revisions\/196"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/hoclaptrinh.fun\/index.php\/wp-json\/wp\/v2\/media\/188"}],"wp:attachment":[{"href":"https:\/\/hoclaptrinh.fun\/index.php\/wp-json\/wp\/v2\/media?parent=186"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/hoclaptrinh.fun\/index.php\/wp-json\/wp\/v2\/categories?post=186"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/hoclaptrinh.fun\/index.php\/wp-json\/wp\/v2\/tags?post=186"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}