What Are Design principles? Design P rinciples are guidelines that helps us avoid bad design What is a bad design? Rigidity: Very difficult to change the system, as it affects a lot of components Fragility: Any change causes unexpected parts of system break Immobility: The system is very hard to reuse 2
Single Responsibility principle A component should have only one reason to change. Which one is your drawer? Proposed by Robert Cecil Martin aka Uncle Bob Code changes are easy, fewer side effects Code becomes more cohesive, less coupled Easy debugging and testability 3
Smells A Constructor with too many parameters Method with too many parameters Code is too long Code is very difficult to test Shotgun effect 4
Open close principle Components should be open for extension but closed for modifications . Proposed by Bertrand Meyer Which shape are you? Primarily implemented using inheritance Helps a change confined to newer parts of system. 5
SMELLS Duplicated code that can reside in higher abstractions If adding similar functionality is difficult 6
Liskov Substitution principle O bjects in a program should be replaceable with instances of their subtypes without altering the correctness of that program. Proposed by Barbara Liskov Are you a square? Extension of Open Close principle 7
Liskov Substitution principle CONTD No new parameters Contra-variance of method a rguments in the subtype Covariance of return t ypes in the subtype No New Exceptions 8
SMELLS Overusing inheritance 9
INTERFACE SEGREGATION principle C lients should not be forced to implement interfaces they don't use Proposed by Robert Cecil Martin To mail or to dial? Could be violated due to fat interfaces Increases the flexibility of the code Could result in lots of interfaces with single methods 10
Smells Interfaces that violate SRP Introducing new implementations breaks existing behavior Could result in proliferation of interfaces 11
Dependency Inversion principle Abstractions should not depend on details. High-level components should not depend on low level modules. They should depend on abstractions of implementations. How would you transfer your money? Components can be easily changed by changing implementations 12
SMELLS Providing alternate implementation is difficult Code is tightly coupled 13
SOLID Principles What you went through are called SOLID principles There are lots of principles in OOP But we will only discuss three more 14
YAGNI You A in’t Gonna Need It You already know it S hould not add functionality until deemed necessary No gold plating By Martin Fowler 15
DRY Don’t Repeat Yourself Make use of OOP paradigms intelligently Could introduce complexity in your code 16
KISS Keep It Simple, Stupid YAGNI is about keeping only necessary code KISS is about making the remaining code simple Its about Performance, Correctness and Readability 17
Questions? 18
Food for thought Kiss vs DRY, how would you choose?