0.00 solid principles - amresh087/Question GitHub Wiki

Why solid principles ?

To create understandable, readable, and testable code that many can work together

S.O.L.I.D Principles

1. Single Responsible Principle

One class = One job.

Real-Time Project Example

In a Spring Boot Microservice:

Loan Processing System

Separate classes:

  • LoanValidationService
  • LoanRepository
  • NotificationService
  • AuditService

Each class has only one responsibility.

2. Open-closed Principle

Open for extension, closed for modification

Step 1: Create Interface

        public interface Payment {
            void pay();
          }

Step 2: Implement Different Payments

Card Payment public class CardPayment implements Payment {

            @Override
            public void pay() {
                System.out.println("Card Payment");
            }
        }

UPI Payment

        public class UpiPayment implements Payment {

            @Override
            public void pay() {
                System.out.println("UPI Payment");
            }
        }

Step 3: Main Service

        public class PaymentService {

            public void processPayment(Payment payment) {
                payment.pay();
            }
        }

Now Add New Feature WITHOUT Modification

Wallet Payment

        public class WalletPayment implements Payment {

            @Override
            public void pay() {
                System.out.println("Wallet Payment");
            }
        }

3. Liskov Substitution

Child class should behave like parent

Parent Interface

        interface Payment {
            void pay();
        }

Good Child Classes

        class CreditCardPayment implements Payment
        class UpiPayment implements Payment

Both behave properly.

4. Interface Segregation

Don’t force classes to implement unnecessary methods

Suppose you have interface called shape. In this interface having a method called getArea() then we can implement this interface Rectangle, square, circle. If I want to implement in Qube class then it is not good because in Qube no need

So we need create Segregation interface like below

 interface Shape{
   //defined some some method that can use in 2DShape and 3DShape  
}

 interface 2DShape extends Shape{
   //defined some some method that can use in 2DShape 
 }

interface 3DShape extends Shape{
   //defined some some method that can use in 3DShape  
}

5. Dependency Inversion

Depend on abstraction, not concrete class

Suppose you have a class called Printer with print method. But in future we need implement CsvPrinter then we need to create interface and that interface used in both classes. where we need call then create indirect object