Code

SOLID principles in OOP: what they are and how to apply them

SOLID principles in OOP: what they are and how to apply them

Course with employment: "The Java Developer Profession"

Learn more

SOLID is a set of five core principles for class design in object-oriented programming. These principles promote the creation of code that is easy to understand, modify, and maintain. Applying SOLID principles makes the application architecture more robust and simplifies its further development. In this article, we will examine each of the principles in detail and provide examples in Java. Make a cup of coffee or tea, and let's begin our acquaintance with SOLID.

The table of contents is an important element of any text, as it allows the reader to quickly navigate the main content. A well-written table of contents improves readability and helps users find the information they need. Optimizing content for SEO involves using relevant keywords and structuring the text to improve search engine visibility.

When creating content, it's important to consider the target audience and their interests. This will not only attract attention but also keep readers on the page. Using subheadings and lists can also improve information comprehension.

It's important to remember that content should be relevant and useful to readers, which helps build trust in the resource. Optimized content not only improves user experience but also helps improve a website's ranking in search results, which is a key aspect of a successful online presence.

  • What is SOLID
  • Single Responsibility Principle: SRP
  • Open Closed Principle: OCP
  • Liskov Substitution Principle: LSP
  • Interface Segregation Principle: ISP
  • Dependency Inversion Principle: DIP

What is SOLID and why was it invented?

The SOLID principles were formulated by the American software engineer Robert S. Martin. In the early 2000s, he systematized approaches to object-oriented design in the article "Design Principles and Design Patterns." In 2004, development consultant Michael Feathers proposed uniting these ideas under the acronym SOLID, which has become a symbol of quality programming and software design. SOLID principles help developers create more understandable, flexible, and maintainable code, which in turn reduces errors and improves team efficiency. These principles cover such key aspects as separation of concerns, openness for extension, and closure for modification, which can significantly improve the architecture of software systems.

  • S — Single Responsibility Principle.
  • O — Open-Closed Principle.
  • L — Liskov Substitution Principle.
  • I — Interface Segregation Principle.
  • D — Dependency Inversion Principle.

These principles contribute to the effective solution of common problems in object-oriented programming. They help developers create more robust, maintainable, and understandable code, which ultimately improves the quality of software. Applying these principles helps improve the structure of code, makes it easier to modify and test, and reduces the likelihood of errors. By using these approaches, programmers can significantly improve development efficiency and simplify future work with projects.

  • Tightly coupled classes: changing one affects others.
  • Testing difficulties: components are tightly coupled, making them difficult to test individually.
  • Extensibility issues: adding new features often requires reworking existing code.
  • Instability to change: one change can break the entire application.

Application of SOLID principles promotes the development of a flexible architecture, where each application component is responsible for performing its specific task without interfering with the work of others. This approach significantly simplifies testing, maintenance, and code refinement. Changes in one part of the system do not cause unexpected problems in other modules, which increases the reliability and stability of the application. Using SOLID principles allows developers to create more scalable and manageable solutions, which ultimately improves software quality and speeds up the development process.

In the following sections, we will cover the main principles in detail and provide an opportunity to apply them in practice. To fully understand the material, you will need basic knowledge of Java and the fundamentals of object-oriented programming (OOP). If you are at the beginning stage of learning programming, we recommend that you first read the relevant articles. This will help you better understand the material presented and successfully apply the learned principles in your projects.

  • How to install the JDK and the IntelliJ IDEA IDE
  • Classes and objects in Java
  • Abstract classes in Java and their differences from interfaces: short and simple

If you prefer, you can use VS Code with the Extension Pack for Java installed instead of IntelliJ IDEA. This solution is perfectly suitable for running the examples presented in this article, as they are designed with simplicity in mind. For example, the examples declare fields without the private access modifier, lack getters and setters, and instead of complex logic, use simple console output using System.out.println().

In real-world projects, the code becomes more complex, incorporating thoughtful architecture, various levels of abstraction, interfaces, testing, and other best practices. However, when you're just beginning to learn SOLID principles, such aspects can distract from a core understanding of the concepts. It's important to focus on the key principles so you can apply them effectively in the future when you encounter more complex problems. Understanding SOLID will help you create more robust and maintainable code, which in turn will improve the quality of your software products.

Single Responsibility Principle: SRP

The single responsibility principle states that each class should perform only one task. Changes to a class should occur only if the logic related to its responsibility changes. This principle improves the structure and readability of code, making it easier to maintain and test. Adhering to the single responsibility principle allows developers to create more robust and flexible systems where changes to one class do not affect other components.

In our example, we will create a Book class, which will contain information about a book, such as the title, author, and price. We will also add an Invoice class, which will be responsible for generating an invoice at a bookstore. Let's consider how this can be implemented in code. The Invoice class will use data from the Book class to create a detailed invoice, including purchase information and the total price. This will allow for efficient sales management and improve the user experience.

At first glance, everything seems logical, but in practice, this class violates the first principle of SOLID in several respects. The single responsibility principle states that a class should have only one reason to change. Violating this principle leads to difficulties in maintaining and extending code. Instead of focusing on a single role, the class takes on multiple functions, which complicates its testing and use. Effective software architecture requires a clear separation of concerns, which allows for better manageability and flexibility of the system.

  • The printInvoice() method is responsible for printing the invoice. If you need to change the display format—for example, add PDF or HTML support—you will have to edit the Invoice class itself, which violates the single responsibility principle. Display logic should not mix with business logic.
  • The saveToFile() method is responsible for saving the invoice to a file. But if you need to save data in the future, for example, to a database or send it via an API, you'll have to edit the Invoice class again.

A single class performs three key tasks: it calculates the total cost, generates an invoice, and saves the data to a file. However, any change to the methods for outputting information or storing data requires modifications to the business logic. This violates the single responsibility principle (SRP) and complicates subsequent code maintenance, which can lead to errors and difficulties in development. Optimizing the architecture will help improve the support and flexibility of the system.

SRP Violation: Invoice Combines Calculation, Output, and Saving Logic Image: Mermaid Chart / Skillbox Media

To enforce the single responsibility principle, we'll separate the functionality into three classes. The Invoice class will be responsible for calculating the order price, the InvoicePrinter class will print the invoice, and the InvoicePersistence class will store it. This approach improves the structure of the code, making it more readable and maintainable. Each class will focus on its own task, increasing flexibility and simplifying future changes and extensions to the system.

With this separation, each component performs its own specific task. This allows you to easily change the output format in the InvoicePrinter class or the data storage method in InvoicePersistence without affecting the business logic of the Invoice class. This approach significantly increases the flexibility of the code and simplifies its maintenance.

Each class is responsible for its own purpose: Invoice — for data and calculation, InvoicePrinter — for output, InvoicePersistence — for saving. Image: Mermaid Chart / Skillbox Media

Open Closed Principle: OCP — Open Closed Principle

According to the open/closed principle, code should be designed in such a way that it can be extended without having to change the existing implementation. To add new functionality, it is recommended to create new classes or modules rather than making changes to existing ones. This helps maintain the stability and predictability of the code. Most often, interfaces or abstract classes are used to achieve this goal, which provide flexibility and the ability to further extend functionality without the risk of breaking existing code.

If we already have an invoicing application and need to add the functionality of saving invoices to the database, the first step is to implement the saveToDatabase() method in the InvoicePersistence class. This will make it possible to save invoice data in the storage. It is important to keep in mind that when developing such a method, it is necessary to follow software design principles to ensure the flexibility and extensibility of the system.

It is recommended to first define the database structure to understand how exactly invoices will be stored. Then, a method should be implemented that will not only store invoices but also handle possible errors, such as duplicate data or database connection problems. It is also worth providing the ability to retrieve invoices from the database so that users can view and manage them.

When adding this functionality, performance optimization and data security should be considered. This includes the use of parameterized queries to prevent SQL injection attacks and proper transaction management. Therefore, implementing invoice storage in the database will not only improve the functionality of the application but also increase its reliability and security.

When running the code, the console displays the program execution result. The output can contain both text messages and data obtained during the execution of operations. This allows developers to monitor the application's process and identify possible errors. Console output is an important tool for debugging and code analysis, as it provides information about the state of the program and its variables at each stage of execution. Correctly interpreting console output helps optimize code and improve its performance.

At first glance, everything seems logical, but there's one problem. If we decide to implement new data storage methods, we'll have to modify this class again. This contradicts the second SOLID principle, which states that extending functionality should avoid changing existing code. To maintain system flexibility and scalability, you should apply design principles that allow you to add new functionality without changing existing code.

OCP Violation: InvoicePersistence Must Be Changed When Adding New Saving MethodsImage: Mermaid Chart / Skillbox Media

To support the open/closed principle, we will develop the InvoicePersistence interface, which will serve as the basis for various data storage implementations. We will create the FilePersistence class for working with files and the DatabasePersistence class for interacting with databases. This approach will allow you to easily add new data storage methods without changing the existing code. This will ensure the flexibility and scalability of the system, which is especially important when expanding the functionality.

When you run the code in its current form, a message will be displayed in the console.

If you uncomment the line with DatabasePersistence and comment out FilePersistence, you will get a different result. This change will affect the data storage method, which can significantly change the functionality of your program. Using DatabasePersistence provides a more reliable and scalable solution for storing information compared to FilePersistence.

If you need to save an invoice in a different way, we can easily integrate the new class with the necessary logic. At the same time, the current code, which has already been tested and is functioning, will remain unchanged. This will ensure the stability of the system and will allow the implementation of new functions without risk to already implemented solutions.

OCP principle: new classes (FilePersistence, DatabasePersistence) are added without changing the existing code. Image: Mermaid Chart / Skillbox Media

Liskov Substitution Principle: LSP - Liskov Substitution Principle

The Liskov Substitution Principle (LSP) is a key aspect of object-oriented programming that concerns inheritance. It states that if a program uses a base class, each subclass should function as correctly as its parent class. This means that the subclass should not violate the expected behavior of the program, thereby ensuring predictability and stability of the code. Adherence to this principle allows you to create more reliable and maintainable software solutions, improving their scalability and simplifying the debugging process.

Create a Rectangle class to represent a rectangle and calculate its area. Additionally, you need to implement a Square class, which is a specialized version of a rectangle with equal sides. The Square class will inherit from the Rectangle class and use its methods to calculate area, providing a more convenient interface for working with squares.

At first glance, it may seem that changing the width of a square automatically changes its height, and vice versa. However, in some cases, this can lead to unexpected results. For example, code designed to work with a rectangle with a fixed height may not work as expected if a Square object is passed to it. This is because a square is a special case of a rectangle, and its properties must be taken into account in programming. Therefore, it is important to design your code correctly to avoid errors when using objects of different types, especially when they have similar characteristics but differ in behavior.

Calling the AreaFixedHeight.getArea(sq) method causes unexpected behavior. This method is designed for Rectangle objects and assumes that changing the height doesn't affect the width. However, in the Square class, the setHeight() method is overridden in such a way that it changes both parameters simultaneously. This violates the third SOLID principle: the behavior of a subclass differs from that of its base class, which can cause errors and undesirable consequences in the program. This situation highlights the importance of adhering to object-oriented programming principles to ensure the correctness and predictability of class behavior.

LSP Violation: The Square Class Inherits from Rectangle, but Overrides Methods in a Way That Breaks Expected BehaviorImage: Mermaid Chart / Skillbox Media

In our example, the Square class should not inherit from the Rectangle class, as their behavior is significantly different. Instead, it makes more sense to create a common Shape interface and implement it separately in each class. This approach avoids substitution problems and complies with the Liskov Substitution Principle (LSP), thereby providing a more flexible and robust architecture.

The console log is an important tool for developers, allowing them to monitor and analyze code execution. It provides information about various events, errors, and warnings, which aids in debugging and optimizing applications. The console log can include error messages, function execution results, and information about the state of variables during program execution. Effective use of console logging improves code quality and simplifies the process of identifying and fixing problems. The importance of the console log increases when working with large projects, where identifying errors can be time-consuming. Therefore, developers are encouraged to actively use console logs to optimize their applications.

Rectangle and Square are now independent classes, each implementing the Shape interface. The Rectangle class provides flexibility in managing width and height, while the Square class ensures that all sides are equal, making it ideal for working with square shapes. This class structure improves code readability and facilitates its further extension, allowing developers to use polymorphism more effectively in their projects.

LSP compliance: Rectangle and Square implement the common Shape interface - substitution works correctly, without breaking behavior. Image: Mermaid Chart / Skillbox Media

Interface Segregation Principle: ISP

The Interface Segregation Principle (ISP) suggests that interfaces should be narrow and focused. Instead of creating one large interface, it is more effective to develop several smaller ones, each performing its own specific task. This approach allows classes to implement only the methods necessary for their functioning. This not only simplifies the use of interfaces but also improves the flexibility and maintainability of code. Implementing the ISP helps avoid redundancy and reduces the number of changes to classes as requirements change, allowing developers to focus on the most important aspects of their work.

Consider the Employee interface, which includes three main employee responsibilities: work performance, food, and rest. Now let's create a program that implements this interface and demonstrates its functionality.

The result of program execution is the final output, which demonstrates how the program processed the input data. It is important to note that this result may vary depending on the execution conditions and input parameters. Effective program testing allows you to identify potential errors and optimize algorithms, which ultimately contributes to increased performance and accuracy. Correct interpretation of the results is also important for further analysis and decision-making based on the obtained data, which makes understanding the result of program execution a key aspect of software development.

Each class implementing the Employee interface is required to provide full implementations of all three methods. Consider two employees:

  • Developer - works, lunch, and rest.
  • Manager - only works, without lunches and breaks.

In this situation, the manager is forced to implement unnecessary methods, which leads to a violation of the principle of interface segregation. This approach not only complicates the code but also reduces its readability and support. Effective interface design should be clear and minimalist, allowing developers to use only the functionality they need.

ISP Violation: The Employee Interface Includes Everything, forcing Developers to Implement Even Unneeded Methods Image: Mermaid Chart / Skillbox Media

It is recommended to split the Employee interface into several narrow interfaces. This will allow each class to implement only the methods it really needs. This approach improves the flexibility and readability of code and promotes adherence to SOLID principles, especially the interface segregation principle. Narrow interfaces help avoid unnecessary dependencies of classes on methods they do not use, which in turn improves the maintainability and testing of the application.

The information presented in the console is an important source of data that helps developers and users monitor program execution and identify errors. The console displays error messages, warnings, and other information, significantly simplifying the process of debugging code. Effective use of the console can improve development productivity and ensure a higher quality of the final product. Correctly interpreting the information displayed in the console helps quickly identify and resolve issues, which in turn contributes to a smoother and more efficient software development and testing process.

The Employee interface is now divided into three distinct components: Workable, Lunchable, and Breakable. This improvement allows for more efficient management of various aspects of the workflow, providing flexibility and ease of use. Each of these interfaces performs specific functions, helping to optimize employee interaction with the system. The division into three interfaces allows for better organization of work time, lunch breaks, and other breaks, ultimately increasing overall productivity.

  • Developer implements all three—it works, eats lunch, and rests.
  • Manager implements only Workable—nothing extra.

This approach fully complies with the interface segregation principle of the SOLID methodology. Each class implements only the methods it needs, avoiding unnecessary and redundant implementations. This contributes to cleaner code architecture, improving its readability and maintainability. Applying the interface segregation principle also facilitates testing and modification of the system, since changes to one class minimally affect other components. Thus, following this principle can significantly improve the quality and efficiency of software development.

ISP compliance: interfaces are separated by tasks - each class implements only the necessary methods. Image: Mermaid Chart / Skillbox Media

Dependency Inversion Principle: DIP - Dependency Inversion Principle

The Dependency Inversion Principle (DIP) states that high-level modules should be based on abstractions rather than on concrete low-level modules. High-level modules represent the business logic of an application, including aspects such as user management and order processing, while low-level modules relate to specific technical decisions, such as interaction with databases, APIs, or file systems. This principle promotes code flexibility and testability by allowing developers to easily replace low-level implementations without affecting business logic. Inverse dependency makes a system more resilient to change and improves software maintainability.

If a class has a direct dependency on a specific implementation, testing and modification become difficult. Robert Martin emphasizes that such a dependency limits flexibility and complicates code maintenance. To improve testability and simplify modifications, it is recommended to use dependency inversion principles and interfaces. This allows for the creation of more abstract solutions that are easily adaptable to changes and ensure greater resilience of the system as a whole.

OCP, or the Open/Closed Principle, defines the primary goal of object-oriented architecture, while DIP, or the Dependency Inversion Principle, serves as a key mechanism for achieving this goal. Implementing DIP allows developers to create more flexible and scalable systems by reducing the coupling of components and facilitating their testing and modification. As a result, applying these principles contributes to the creation of high-quality software that meets the demands of the modern market.

These two principles are interrelated: to ensure that classes are open for extension (OCP), it is necessary to get rid of rigid dependencies in favor of abstractions (DIP). You can think of this using the example of a LEGO set: instead of the pieces being firmly glued together, they are connected via standard connectors, similar to interfaces in programming. This allows for easy replacement of some elements with others without breaking the overall structure. Applying these principles helps create flexible and scalable code, which is especially important in modern software development.

The OrderService class is designed to process orders and has a direct dependency on a specific database implementation, in this case, the MySQLDatabase class. This allows OrderService to effectively interact with the database, performing operations such as creating, updating, and deleting orders. Using MySQLDatabase as a dependency ensures reliability and performance of data processing. Optimization of this class can include the implementation of design patterns such as dependency injection, which will increase flexibility and simplify testing of OrderService using different database implementations.

The result of code execution is the output obtained after processing a request or executing certain instructions in the program. It can include data, error messages, graphical elements, or other visual representations. It is important to understand that the result of code execution depends on the logic of the program, the input data, and the conditions specified by the developer. To optimize code and improve its performance, you should carefully analyze the results obtained and make any necessary adjustments. Effective management of code execution results improves software quality and user satisfaction.

In the example given, the OrderService class is directly linked to MySQLDatabase, resulting in the creation of an object within the class itself. This limits the ability to replace the database or test the service without connecting to a real database. This dependency violates the Dependency Inversion Principle (DIP), as business logic becomes dependent on a specific implementation rather than abstractions. To improve the application architecture and make it more flexible, interfaces or abstract classes should be used for working with databases. This will make it easy to swap out implementations and test services without having to change their source code.

DIP Violation: OrderService Depends on MySQL Database, Complicating Code Testing and Reuse Image: Mermaid Chart / Skillbox Media

We will develop an interface that will serve as an abstraction for efficient data storage. This interface will provide convenient access to and processing of data, allowing users to easily interact with various information sources. We will focus on creating a flexible structure that supports scalability and ease of integration with other system components.

The message displayed in the console is an important tool for developers. It provides information about the application state, warnings about possible errors, and debugging information. Console messages help track code execution and identify problems early in the development process. Understanding and correctly using console messages significantly simplifies the process of debugging and improving the quality of web applications. Developers should pay attention not only to the content of messages but also to their format to make them more informative and useful.

Now, OrderService relies not on a concrete repository implementation, but on an abstraction—the OrderRepository interface. This approach allows you to connect different data storage implementations, such as MySQL, MongoDB, and others, without having to change the service's code itself. This is the principle of dependency inversion: high-level modules should depend on abstractions, not on specific implementations. This makes the system more flexible and easily scalable, simplifying the process of updating and support.

DIP compliance: OrderService depends on the OrderRepository interface, not on a specific database implementation. Image: Mermaid Chart / Skillbox Media

Learn more about coding and programming in our Telegram channel. Subscribe to stay up to date with interesting content and helpful tips!

Also read:

  • Basic Java Design Patterns
  • Java Core for Beginners: Roadmap
  • Java Code Style: How to Properly Format Java Code