SlideShare una empresa de Scribd logo
1 de 35
Hithesh N
Associate software engineer
Single Responsibility Principle
Open/Closed Principle
Liskov Substitution Principle
Inter face Segregation Principle
Dependency Inversion Principle
Code becomes more Testably (remember TDD is
not only about testing, more important its about
Design)
Apply ’smart’
- don’t do stuff ’just because of’
- very importad to see the context of the
program/code when applying SOLID
- Joel On Software advise – use with common
sense!
 How can we tell when our code is rotting?
Rigidity

 Design is to hard change
Fragility

 Design is easy to break
Immobility

 Design is hard to reuse
Viscosity

 Design makes hard to do the right thing
Definition
 “Every object should have a single
responsibility and that responsibility should
be entirely encapsulated by the class”

 “Class should have one responsibility - one
reason to change”
 My translation: A class should concentrate
on doing one thing and one thing only
Example
 Two resposibilities

interface Modem {
public void dial(String pno);
public void hangup();
public void send(char c);
public char recv();
}

 Connection Management + Data Communication
 Separate into two interfaces
interface DataChannel {
public void send(char c);
public char recv();
}

interface Connection {
public void dial(String phn);
public char hangup();
}
Argument Against SRP
 “To Many classes and too difficult to understand the
BIG PICTURE”
 There are no more moving parts in a system with many
small pieces than that with a few large pieces. The
benefits outweigh this argument. Consistency, Good
names and documentation make this a mute point.
What are some of the benefits
 Reuse - If all your class follow the SRP,you are more likely to reuse
some of them
 Clarity - Your code is cleaner as your class don’t do unexpected
things
 Naming –As all your classes have a single responsibility, choosing
a good name easy
 Readability –Due to the clarity, better names and shorter files the
readability is improved greatly

 Smaller Function -
 A module should be open to Extensibility ,but closed for
modification
 My translation: Change a class' behavior using
inheritance and composition
Example
// Open-Close Principle - Bad example
class GraphicEditor {
public void drawShape(Shape s) {
if (s.m_type==1)
drawRectangle(s);
else if (s.m_type==2)
drawCircle(s);
}
public void drawCircle(Circle r) {....}
public void drawRectangle(Rectangle r) {....}
}
class Shape {
int m_type;
}
class Rectangle extends Shape {
Rectangle() {
super.m_type=1;
}
}
class Circle extends Shape {
Circle() {
super.m_type=2;
}
}
Open Closed Principle – a Few Problems…
 Impossible to add a new Shape without modifying
GraphEditor
 Important to understand GraphEditor to add a new
Shape
 Tight coupling between GraphEditor and Shape

 Difficult to test a specific Shape without involving
GraphEditor
 If-Else-/Case should be avoided
Open Closed Principle - Improved
 // Open-Close Principle - Good example
class GraphicEditor {
public void drawShape(Shape s) {
s.draw();
}
}
class Shape {
abstract void draw();
}
class Rectangle extends Shape {
public void draw() {
// draw the rectangle
}
}
Challenges with using OCP?
Challenges
 Expensive – Requires significant effort

 Experience – best judgment

 Research – ask the right question
Liskov Substitution Principle

 “Derived classes must be substitutable for their base
class”
 My translation: Subclasses should behave nicely when
used in place of their base class
Liskov Substitution Principle
class Square extends Rectangle
// Violation of Liskov's Substitution Principle
{
class Rectangle
public void setWidth(int width){
{
m_width = width;
int m_width;
m_height = width;
int m_height;
}
public void setWidth(int width){
m_width = width;
}
public void setHeight(int h){
m_height = ht;
}

public int getWidth(){
return m_width;
}
public int getHeight(){
return m_height;
}
public int getArea(){
return m_width * m_height;
}
}

public void setHeight(int height){
m_width = height;
m_height = height;
}
}
Liskov Substitution Principle
class LspTest
{
private static Rectangle getNewRectangle()
{
// it can be an object returned by some factory ...
return new Square();
}
public static void main (String args[])
{
Rectangle r = LspTest.getNewRectangle();
r.setWidth(5);
r.setHeight(10);
// user knows that r it's a rectangle. It assumes that he's
able to set the width and height as for the base class
System.out.println(r.getArea());
// now he's surprised to see that the area is 100
instead of 50.
}
}
Interface Segregation Principle
 "Clients should not be forced to depend upon
interfaces that they do not use.“

 My translation: Keep interfaces small
Interface Segregation Principle
//bad example (polluted interface)
interface Worker {
void work();
void eat();
}

ManWorker implements Worker {
void work() {…};
void eat() {30 min
break;};

}

RobotWorker implements Worker {
void work() {…};
void eat() {//Not
Appliciable
for a
RobotWorker};
Interface Segregation Principle
 Solution
- split into two interfaces

interface Workable {
public void work();
}

interface Feedable{
public void eat();
}
Dependency Inversion Principle
 A. High level modules should not depend upon low level
modules. Both should depend upon abstractions.
B. Abstractions should not depend upon details. Details
should depend upon abstractions.“
 My translation: Use lots of interfaces and abstractions
Dependency Inversion Principle
//DIP - bad example
public class EmployeeService {
private EmployeeFinder emFinder //concrete class, not abstract.
Can access a SQL DB for instance
public Employee findEmployee(…) {
emFinder.findEmployee(…)
}
}
Dependency Inversion Principle
//DIP - fixed
public class EmployeeService {
private IEmployeeFinder emFinder //depends on an abstraction,
no animplementation
public Employee findEmployee(…) {

emFinder.findEmployee(…)
}
}

Now its possible to change the finder to be a
XmlEmployeeFinder, DBEmployeeFinder,
FlatFileEmployeeFinder, MockEmployeeFinder….
Q&A

http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOo
d
http://www.oodesign.com
http://www.slideshare.net/enbohm

Más contenido relacionado

La actualidad más candente

Classes and data abstraction
Classes and data abstractionClasses and data abstraction
Classes and data abstractionHoang Nguyen
 
Java OOP Programming language (Part 6) - Abstract Class & Interface
Java OOP Programming language (Part 6) - Abstract Class & InterfaceJava OOP Programming language (Part 6) - Abstract Class & Interface
Java OOP Programming language (Part 6) - Abstract Class & InterfaceOUM SAOKOSAL
 
Abstract data types
Abstract data typesAbstract data types
Abstract data typesHoang Nguyen
 
Lecture 9 access modifiers and packages
Lecture   9 access modifiers and packagesLecture   9 access modifiers and packages
Lecture 9 access modifiers and packagesmanish kumar
 
SOLID mit Java 8
SOLID mit Java 8SOLID mit Java 8
SOLID mit Java 8Roland Mast
 
Ch.1 oop introduction, classes and objects
Ch.1 oop introduction, classes and objectsCh.1 oop introduction, classes and objects
Ch.1 oop introduction, classes and objectsITNet
 
What are Abstract Classes in Java | Edureka
What are Abstract Classes in Java | EdurekaWhat are Abstract Classes in Java | Edureka
What are Abstract Classes in Java | EdurekaEdureka!
 
Support for Object-Oriented Programming (OOP) in C++
Support for Object-Oriented Programming (OOP) in C++Support for Object-Oriented Programming (OOP) in C++
Support for Object-Oriented Programming (OOP) in C++Ameen Sha'arawi
 
Lecture18 structurein c.ppt
Lecture18 structurein c.pptLecture18 structurein c.ppt
Lecture18 structurein c.ppteShikshak
 
Abstract Class Presentation
Abstract Class PresentationAbstract Class Presentation
Abstract Class Presentationtigerwarn
 

La actualidad más candente (20)

Java interface
Java interfaceJava interface
Java interface
 
Abstract classes and interfaces
Abstract classes and interfacesAbstract classes and interfaces
Abstract classes and interfaces
 
Classes and data abstraction
Classes and data abstractionClasses and data abstraction
Classes and data abstraction
 
Structures
StructuresStructures
Structures
 
Java OOP Programming language (Part 6) - Abstract Class & Interface
Java OOP Programming language (Part 6) - Abstract Class & InterfaceJava OOP Programming language (Part 6) - Abstract Class & Interface
Java OOP Programming language (Part 6) - Abstract Class & Interface
 
Structure in c#
Structure in c#Structure in c#
Structure in c#
 
Abstract data types
Abstract data typesAbstract data types
Abstract data types
 
Abstraction file
Abstraction fileAbstraction file
Abstraction file
 
SOLID Java Code
SOLID Java CodeSOLID Java Code
SOLID Java Code
 
Lecture 9 access modifiers and packages
Lecture   9 access modifiers and packagesLecture   9 access modifiers and packages
Lecture 9 access modifiers and packages
 
SOLID mit Java 8
SOLID mit Java 8SOLID mit Java 8
SOLID mit Java 8
 
Abstract method
Abstract methodAbstract method
Abstract method
 
Ch.1 oop introduction, classes and objects
Ch.1 oop introduction, classes and objectsCh.1 oop introduction, classes and objects
Ch.1 oop introduction, classes and objects
 
What are Abstract Classes in Java | Edureka
What are Abstract Classes in Java | EdurekaWhat are Abstract Classes in Java | Edureka
What are Abstract Classes in Java | Edureka
 
javainterface
javainterfacejavainterface
javainterface
 
Support for Object-Oriented Programming (OOP) in C++
Support for Object-Oriented Programming (OOP) in C++Support for Object-Oriented Programming (OOP) in C++
Support for Object-Oriented Programming (OOP) in C++
 
Lecture18 structurein c.ppt
Lecture18 structurein c.pptLecture18 structurein c.ppt
Lecture18 structurein c.ppt
 
Poo java
Poo javaPoo java
Poo java
 
Abstract classes
Abstract classesAbstract classes
Abstract classes
 
Abstract Class Presentation
Abstract Class PresentationAbstract Class Presentation
Abstract Class Presentation
 

Similar a Solid Principles

Similar a Solid Principles (20)

An Introduction to the SOLID Principles
An Introduction to the SOLID PrinciplesAn Introduction to the SOLID Principles
An Introduction to the SOLID Principles
 
SOLID
 SOLID SOLID
SOLID
 
Object Design - Part 1
Object Design - Part 1Object Design - Part 1
Object Design - Part 1
 
SOLID Design Principles
SOLID Design PrinciplesSOLID Design Principles
SOLID Design Principles
 
L04 Software Design 2
L04 Software Design 2L04 Software Design 2
L04 Software Design 2
 
The maze of Design Patterns & SOLID Principles
The maze of Design Patterns & SOLID PrinciplesThe maze of Design Patterns & SOLID Principles
The maze of Design Patterns & SOLID Principles
 
Interface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar SinghInterface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar Singh
 
L22 Design Principles
L22 Design PrinciplesL22 Design Principles
L22 Design Principles
 
L02 Software Design
L02 Software DesignL02 Software Design
L02 Software Design
 
Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3
 
20 Object-oriented programming principles
20 Object-oriented programming principles20 Object-oriented programming principles
20 Object-oriented programming principles
 
SOLID
SOLIDSOLID
SOLID
 
Design pattern
Design patternDesign pattern
Design pattern
 
Solid js
Solid jsSolid js
Solid js
 
Solid principles in action
Solid principles in actionSolid principles in action
Solid principles in action
 
Solid principles - Object oriendte
Solid principles - Object oriendteSolid principles - Object oriendte
Solid principles - Object oriendte
 
Chapter 13 introduction to classes
Chapter 13 introduction to classesChapter 13 introduction to classes
Chapter 13 introduction to classes
 
Design patters java_meetup_slideshare [compatibility mode]
Design patters java_meetup_slideshare [compatibility mode]Design patters java_meetup_slideshare [compatibility mode]
Design patters java_meetup_slideshare [compatibility mode]
 
L03 Software Design
L03 Software DesignL03 Software Design
L03 Software Design
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 

Último

Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 

Último (20)

Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 

Solid Principles

  • 2. Single Responsibility Principle Open/Closed Principle Liskov Substitution Principle Inter face Segregation Principle Dependency Inversion Principle
  • 3. Code becomes more Testably (remember TDD is not only about testing, more important its about Design) Apply ’smart’ - don’t do stuff ’just because of’ - very importad to see the context of the program/code when applying SOLID - Joel On Software advise – use with common sense!
  • 4.
  • 5.  How can we tell when our code is rotting?
  • 6. Rigidity  Design is to hard change
  • 7. Fragility  Design is easy to break
  • 8. Immobility  Design is hard to reuse
  • 9. Viscosity  Design makes hard to do the right thing
  • 10.
  • 11. Definition  “Every object should have a single responsibility and that responsibility should be entirely encapsulated by the class”  “Class should have one responsibility - one reason to change”  My translation: A class should concentrate on doing one thing and one thing only
  • 12. Example  Two resposibilities interface Modem { public void dial(String pno); public void hangup(); public void send(char c); public char recv(); }  Connection Management + Data Communication
  • 13.  Separate into two interfaces interface DataChannel { public void send(char c); public char recv(); } interface Connection { public void dial(String phn); public char hangup(); }
  • 14. Argument Against SRP  “To Many classes and too difficult to understand the BIG PICTURE”  There are no more moving parts in a system with many small pieces than that with a few large pieces. The benefits outweigh this argument. Consistency, Good names and documentation make this a mute point.
  • 15. What are some of the benefits  Reuse - If all your class follow the SRP,you are more likely to reuse some of them  Clarity - Your code is cleaner as your class don’t do unexpected things  Naming –As all your classes have a single responsibility, choosing a good name easy  Readability –Due to the clarity, better names and shorter files the readability is improved greatly  Smaller Function -
  • 16.
  • 17.  A module should be open to Extensibility ,but closed for modification  My translation: Change a class' behavior using inheritance and composition
  • 18. Example // Open-Close Principle - Bad example class GraphicEditor { public void drawShape(Shape s) { if (s.m_type==1) drawRectangle(s); else if (s.m_type==2) drawCircle(s); } public void drawCircle(Circle r) {....} public void drawRectangle(Rectangle r) {....} } class Shape { int m_type; } class Rectangle extends Shape { Rectangle() { super.m_type=1; } } class Circle extends Shape { Circle() { super.m_type=2; } }
  • 19. Open Closed Principle – a Few Problems…  Impossible to add a new Shape without modifying GraphEditor  Important to understand GraphEditor to add a new Shape  Tight coupling between GraphEditor and Shape  Difficult to test a specific Shape without involving GraphEditor  If-Else-/Case should be avoided
  • 20. Open Closed Principle - Improved  // Open-Close Principle - Good example class GraphicEditor { public void drawShape(Shape s) { s.draw(); } } class Shape { abstract void draw(); } class Rectangle extends Shape { public void draw() { // draw the rectangle } }
  • 22. Challenges  Expensive – Requires significant effort  Experience – best judgment  Research – ask the right question
  • 23.
  • 24. Liskov Substitution Principle  “Derived classes must be substitutable for their base class”  My translation: Subclasses should behave nicely when used in place of their base class
  • 25. Liskov Substitution Principle class Square extends Rectangle // Violation of Liskov's Substitution Principle { class Rectangle public void setWidth(int width){ { m_width = width; int m_width; m_height = width; int m_height; } public void setWidth(int width){ m_width = width; } public void setHeight(int h){ m_height = ht; } public int getWidth(){ return m_width; } public int getHeight(){ return m_height; } public int getArea(){ return m_width * m_height; } } public void setHeight(int height){ m_width = height; m_height = height; } }
  • 26. Liskov Substitution Principle class LspTest { private static Rectangle getNewRectangle() { // it can be an object returned by some factory ... return new Square(); } public static void main (String args[]) { Rectangle r = LspTest.getNewRectangle(); r.setWidth(5); r.setHeight(10); // user knows that r it's a rectangle. It assumes that he's able to set the width and height as for the base class System.out.println(r.getArea()); // now he's surprised to see that the area is 100 instead of 50. } }
  • 27.
  • 28. Interface Segregation Principle  "Clients should not be forced to depend upon interfaces that they do not use.“  My translation: Keep interfaces small
  • 29. Interface Segregation Principle //bad example (polluted interface) interface Worker { void work(); void eat(); } ManWorker implements Worker { void work() {…}; void eat() {30 min break;}; } RobotWorker implements Worker { void work() {…}; void eat() {//Not Appliciable for a RobotWorker};
  • 30. Interface Segregation Principle  Solution - split into two interfaces interface Workable { public void work(); } interface Feedable{ public void eat(); }
  • 31.
  • 32. Dependency Inversion Principle  A. High level modules should not depend upon low level modules. Both should depend upon abstractions. B. Abstractions should not depend upon details. Details should depend upon abstractions.“  My translation: Use lots of interfaces and abstractions
  • 33. Dependency Inversion Principle //DIP - bad example public class EmployeeService { private EmployeeFinder emFinder //concrete class, not abstract. Can access a SQL DB for instance public Employee findEmployee(…) { emFinder.findEmployee(…) } }
  • 34. Dependency Inversion Principle //DIP - fixed public class EmployeeService { private IEmployeeFinder emFinder //depends on an abstraction, no animplementation public Employee findEmployee(…) { emFinder.findEmployee(…) } } Now its possible to change the finder to be a XmlEmployeeFinder, DBEmployeeFinder, FlatFileEmployeeFinder, MockEmployeeFinder….