Solid Principles (SOLID)
SOLID
SOLID basically contains five design principles to make a software deign more maintainable and extendable as per future need.
S - Single Responsibility Principle :
Single responsibility principles says that every java class must have perform single responsibility, lets take a example of e-commerce, if class is meant for excepting order it should not perform stuff related to payment or send sms.
O - Open Closed Principle:
This principle says that any module should be open for extension but closed for modification.
Suppose class A has a function to calculate area of square only but if some class B want to use this but need to calculate the area of some other shape. In this case class A needs to update but this will violates the open closed principle because we are modifying the class.
To achieve this principle, Class/interface need to define in such a way that another class can extend and provide extended functionality.
L - Leskov's Substitution Principle:
Any subclass object should be substitute for its superclass object.
I - Interface Segregation Principle:
Interface should not force its implementaion class to use that methods which has no significance for the class.
Like if we say Payment Interface has methods DebitCardPayment(), WalletPayment() & CreditCardPayment().
Class DebitCardPayment implements Payment
Then in this case it also needs to provide implementation for WalletPayment() & CreditCardPayment() which is of no use for class DebitCardPayment. So iterface should be segregated.
D - Dependency Inversion Principle:
Define a abstraction between declaration and details, this removes the tight coupling and provide loose coupling.
Instead of referencing a implementation class use interface reference.
example : Let's we have Payment class and make payment with debit, credit card.
Class PaymentImpl{
DebitCard card;
public void PaymentImpl( DebitCard debitCard){
this.card = debitCard;
}
This will work for debit card but for credit card you need to change class. So this violates Dependency Inversion principle.
Correct way :
You need to create a Interface PaymentMethod that will be implement by DebitCard & CreditCard class.
Class PaymentImpl{
PaymentMethod card;
public void PaymentImpl( PaymentMethod card){
this.card = card;
}
Labels: java design principle, Java Solid Principles, Liskov Substitution Principle, SOLID, SOLID design principles, Solid Principles