This principle states that "A class should have only one reason to change" which means every class should have a single responsibility or single job or single purpose. In other words, a class should have only one job or purpose within the software system.
Example: Imagine a baker who is responsible for baking bread. The baker's role is to focus on the task of baking bread, ensuring that the bread is of high quality, properly baked, and meets the bakery's standards.
If the baker handles inventory, ordering, customer service, and cleaning along with baking, it violates SRP since multiple responsibilities are combined.
Each task is a separate responsibility, and combining them reduces the baker’s focus and effectiveness in baking.
To follow SRP, responsibilities should be divided among different individuals or teams, each handling a specific task independently.
BreadBaker Class: Responsible solely for baking bread. This class focuses on ensuring the quality and standards of the bread without being burdened by other tasks.
InventoryManager Class: Handles inventory management, ensuring that the bakery has the right ingredients and supplies available.
SupplyOrder Class: Manages ordering supplies, ensuring that the bakery is stocked with necessary items.
CustomerService Class: Takes care of serving customers, providing a focused approach to customer interactions.
BakeryCleaner Class: Responsible for cleaning the bakery, ensuring a hygienic environment.
2. Open/Closed Principle
This principle states that "Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification" which means you should be able to extend a class behavior, without modifying it.
Example: Imagine you have a class called PaymentProcessor that processes payments for an online store. Initially, the PaymentProcessor class only supports processing payments using credit cards. However, you want to extend its functionality to also support processing payments using PayPal.
Instead of modifying the existing PaymentProcessor class, a new PayPalPaymentProcessor class can be created to add PayPal support.
This keeps the original class unchanged while extending its functionality through a new class.
It follows the Open-Closed Principle by keeping the class closed for modification but open for extension.
Extended Functionality
Now, to add support for PayPal payments, you create a new class PayPalPaymentProcessor that extends PaymentProcessor.
Usage
In your application, you can use either payment processor without modifying the existing code for PaymentProcessor or CreditCardPaymentProcessor.
Explanation of the above code:
Base Class (PaymentProcessor): An abstract class that defines a common interface (processPayment) for all payment processors.
CreditCardPaymentProcessor: Implements payment processing specifically for credit card transactions.
PayPalPaymentProcessor: Extends functionality by handling PayPal payment processing.
Main Function: Uses the PaymentProcessor interface to call processPayment(), allowing flexibility without changing existing code.
3. Liskov's Substitution Principle
The principle was introduced by Barbara Liskov in 1987. According to this principle, "derived or child classes must be able to replace their base or parent classes". This ensures that any subclass can be used in place of its parent class without causing unexpected behavior in the program.
Example: One of the classic examples of this principle is a rectangle having four sides. A rectangle's height can be any value and width can be any value. A square is a rectangle with equal width and height. So we can say that we can extend the properties of the rectangle class into square class.
Replacing the Rectangle with a Square forces constraints (equal sides), which changes the expected behavior of the parent class.
This violates LSP because a derived class should not alter or break the behavior expected from the base class.
Code of above example
Output
Area: 100
Rectangle Class: This is the base class that has properties for width and height. It has methods for calculating the area and for setting width and height.
Square Class: This class inherits from Rectangle but overrides the setWidth and setHeight methods to ensure that changing one dimension affects the other, maintaining the property that all sides are equal.
LSP Violation Example
To see a potential violation of LSP, consider what would happen if you were to use the Square class in a context expecting a Rectangle:
If you substitute a Square where a Rectangle is expected, changing just the width or height would lead to unexpected results because it will change both dimensions.
4. Interface Segregation Principle
This principle applies to interfaces and is similar to the Single Responsibility Principle, focusing on keeping interfaces specific and well-defined. It states that clients should not be forced to depend on methods that are irrelevant to them, avoiding unnecessary dependencies. The goal is to prevent fat interfaces by using multiple small, client-specific interfaces, each with a clear and specific responsibility.
Example: Suppose if you enter a restaurant and you are pure vegetarian. The waiter in that restaurant gave you the menu card which includes vegetarian items, non-vegetarian items, drinks, and sweets.
Customers should receive a menu relevant to their needs (e.g., vegetarian only) instead of a general menu with unnecessary items.
Splitting a common menu into smaller, specific ones reduces unnecessary dependencies and minimizes future changes.
IVegetarianMenu Interface: This interface defines a method to get vegetarian items. It ensures that only classes implementing vegetarian menus will need to provide this functionality.
INonVegetarianMenu Interface: Similar to the vegetarian interface, this one defines a method for getting non-vegetarian items.
IDrinkMenu Interface: This interface defines a method for getting drink items, keeping it separate from food items.
VegetarianMenu Class: Implements the IVegetarianMenu interface and provides a list of vegetarian items.
NonVegetarianMenu Class: Implements the INonVegetarianMenu interface and provides a list of non-vegetarian items.
DrinkMenu Class: Implements the IDrinkMenu interface and provides a list of drink items.
5. Dependency Inversion Principle
The Dependency Inversion Principle (DIP) is a principle in object-oriented design that states that "High-level modules should not depend on low-level modules. Both should depend on abstractions". means "Big parts of your program should not directly depend on small, detailed parts. Instead, both should depend on general ideas (interfaces)". Additionally, abstractions should not depend on details. Details should depend on abstractions(Details should follow the rules).
In simpler terms, the DIP suggests that classes should rely on abstractions (e.g., interfaces or abstract classes) rather than concrete implementations.
This allows for more flexible and decoupled code, making it easier to change implementations without affecting other parts of the codebase.
Example: In a software development team, developers depend on an abstract version control system (e.g., Git) to manage and track changes to the codebase. They don't depend on specific details of how Git works internally.
Code of above example
Output
Committing changes to Git with message: Initial commit
Pushing changes to remote Git repository.
Pulling changes from remote Git repository.
IVersionControl Interface: This defines the operations that any version control system should support, like commit, push, and pull. It serves as an abstraction that decouples high-level code from low-level implementations.
GitVersionControl Class: This class implements the IVersionControl interface, providing specific functionality for managing version control using Git.
DevelopmentTeam Class: This class relies on the IVersionControl interface, meaning it can work with any version control implementation that adheres to the interface. It does not need to know the details of how Git works internally.
Need for SOLID Principles in Object-Oriented Design
The main reasons why solid principles are important in object oriented design:
SOLID principles make code easier to maintain. When each class has a clear responsibility, it's simpler to find where to make changes without affecting unrelated parts of the code.
These principles support growth in software. For example, the Open/Closed Principle allows developers to add new features without changing existing code, making it easier to adapt to new requirements.
SOLID encourages flexibility. By depending on abstractions rather than specific implementations (as in the Dependency Inversion Principle), developers can change components without disrupting the entire system.