Thursday, June 2, 2016

OOP Deisgn Principle (SOLID)

5 principles to design a class SOLID:

SRP (Single Responsibility Principle)

  • 1 Class only 1 responsibility.
  • A class should have one, and only one, reason to change.
  • E.g. Student Class only for Student, teacher Class only for Teacher.
  • e.g. We not write function in every catch there, we will write a Common Log Class and Method, and use all the class. so in future, we just change the common log method. Not 1 by 1.

OCP (Open Closed Principle)

  • be open for extension, but closed for modification.
  • E.g. different shape has different calculate area method, we cannot use if…else to calculate this, in future, it might have new shape.
  • Shape > Abstract class, calculate area > abstract method.
  • Rectangle inherit Shape and override calculate method.

http://joelabrahamsson.com/a-simple-example-of-the-openclosed-principle/

LSP (Liskov Substitution Principle)

  • Derived classes must be substitutable for their base classes.
  • object of a derived class should be able to replace an object of the base class without bringing any errors in the system or modifying the behavior of the base class.
  • New derived classes are extending the base classes without changing their behavior.
  • Not implement method in sub class (so you can loop with Parent class and call Parent Method)
  • Sub class function overrides the base class method to give it new meaning.

http://www.infragistics.com/community/blogs/dhananjay_kumar/archive/2015/06/30/simplifying-the-liskov-substitution-principle-of-solid-in-c.aspx

ISP (Interface Segregation Principle)

  • No client should be forced to depend on methods it does not use.
  • Client only want printer function print ONLY, not scan and photocopy.
  • So you can use interface control how many interface you want.

http://www.codeproject.com/Tips/766045/Interface-Segregation-Principle-ISP-of-SOLID-in-Cs

DIP (Dependency Inversion Principle)
  • High-level modules should not depend on low-level modules. They should both depend on abstractions.
  • Loose Coupling and Dependency Injection.
  • Depend on abstractions, not on concretions. 

No comments:

Post a Comment