S: S stands for single responsibility principle.Each class is responsible for single responsibility.
O: Class shall be open for extension but closed for modification. It means if we are getting new type or behaviour changes we should not do the changes on same class instead shall extend those to new classes. And have strategy interface which will pull concrete implementation depending upon need.
This way we can achieve separation on concerns, existing tested code does not have any issues.
Like we have discount that need to be offered to customer class.
Now depending upon customer we have to provide discount.
Bad approach will be
get discount( String customer type) {
If (type.equals("vip"){
}else (type.equals("premium"){
}
Now in future if more type introduced don't modify existing class instead create 2 separate implementation from day one so that they have their own responsibility.
L: L stands for Liskov substitution.This means that objects of superclass shall be replaced with objects of subclasses without breaking the system.
Let say we have Bird as super class and has fly() method and penguin and sparrow as sub class but in penguin we have thrown exception saying it does not fly. This is violation of Liskov substitution principle becoz
We can't assign
Bird b = new Penguin()
Becoz b.fly() will not work as expected.
How to resolve this?
Create subclasses from Bird and only keep those functionality which will be common to all birds at top level . Down the line can add new classes which have different nature .
I: I stands for Interface segregation Principle. This means that Interface shall not have unnecessary methods which need to be implemented by client forcefully. So if there are methods which are not always required by clients so better would be to keep them in separate interface and the clients which want those can override those methods by implementing different interface.
D: D stands for dependency inversion principle.It states that class shall depend on abstract reference(abstract class or interface) rather than concrete implementation(class) . Here , inversion refers to the dependent classes on which another class depends. In simple terms we shall use abstract classes or interface as dependency to one class not concrete classes.
For eg
Class Car{
Engine engine// This Engine either has to be abstract class or interface.
}
No comments:
Post a Comment