SlideShare a Scribd company logo
1 of 36
Download to read offline
SOLID Principles in Action
Arash Khangaldi: @irLogcat 2018
Agenda
● S — Single Responsibility Principle(S.R.P)
● O — Open-Closed Principle
● L — Liskov Substitution Principle
● I — Interface Segregation Principle
● D — Dependency Inversion Principle
Single Responsibility
A class should have one, and only one, reason to change.
Don’t be Swiss Army Knife!
In the context of the Single Responsibility Principle (SRP) we define a
responsibility as “a reason for change”. If you can think of more than one
motive for changing a class, then that class has more than one responsibility.
Violating Single
Responsibility
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
final Movie movie = movies.get(position);
holder.itemView.setTag(movie);
holder.title.setText(movie.getTitle());
holder.rating.setText(movie.getRating());
String genreStr = "";
for (String str: movie.getGenre()) {
genreStr += str + ", ";
}
genreStr = genreStr.length() > 0 ?
genreStr.substring(0, genreStr.length() - 2) : genreStr;
holder.genre.setText(genreStr);
holder.releaseYear.setText(movie.getYear());
Glide.with(holder.thumbNail.getContext())
.load(movies.get(position)
.getThumbnailUrl())
.into(holder.thumbNail);
}
Fixing Single Responsibility
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
final Movie movie = movies.get(position);
holder.itemView.setTag(movie);
holder.title.setText(movie.getTitle());
holder.rating.setText(movie.getRating());
holder.genre.setText(
ArraysUtil.convertArrayListToString(movie.getGenre()));
holder.releaseYear.setText(movie.getYear());
Glide.with(holder.thumbNail.getContext())
.load(movies.get(position)
.getThumbnailUrl())
.into(holder.thumbNail);
}
Violating Single
Responsibility in Tests
@Test
public void testScenario1And2() {
//...
assertEqual(resultOne, mUnderTest.getScenarioOne());
assertEqual(resultTwo, mUnderTest.getScenarioTwo());
}
Fixing Single Responsibility
@Test
public void testScenarioOne() {
//...
assertEqual(resultOne, mUnderTest.getScenarioOne());
}
@Test
public void testScenarioTwo() {
//...
assertEqual(resultTwo, mUnderTest.getScenarioTwo());
}
Open/Closed Principle
You should be able to extend a classes behavior, without modifying it.
This principle is the foundation for building code that is maintainable and
reusable.
Robert C. Martin
Violating O/C Principle
public class Music {
private String title;
private String uri;
// getters/setters ...
}
public class DataFactory {
public ArrayList<String> fetchUri(ArrayList<Object>...
medias) {
ArrayList<String> uris = new ArrayList<String>();
for (Object media : medias) {
if (media instanceof Music) {
Music music = (Music)media;
uris.add(Music.getUri());
} else if (media instanceof Image) {
Image image = (Image)media;
uris.add(
Environment.getStorageDirectory()+
image.getPath());
} else {
throw new RuntimeException("Media not
supported");
}
}
return uris;
}
}
public class Image {
private String title;
private String user;
private String path;
// getters/setters ...
}
Fixing O/C
public interface Media {
String getPath();
}
public class Music implements Media{
private String title;
private String uri;
// getters/setters ...
@Override
public getPath() {
return //...;
}
}
// Image.java
public class Image implements Media{
private String title;
// getters/setters ...
@Override
public getPath() {
return //...;
}
}
public class DataFactory {
public ArrayList<String> fetchUri(ArrayList<Media>... medias) {
ArrayList<String> uris = new ArrayList<String>();
for (Media media : medias) {
uris.add(shape.getArea());
}
return area;
}
}
The Liskov Substitution Principle (LSP)
Child classes should never break the parent class’ type definitions.
Violating LSP Principle
public interface CustomerLayout {
public void render();
}
public PremiumCustomer implements CustomerLayout {
...
@Override
public void render() {
//logic ...
}
}
public FreeCustomer implements CustomerLayout{
...
@Override
public void render() {
if (!hasSeenAd)
return;
//logic ...
}
}
public void renderView(CustomerLayout layout) {
layout.render();
}
Fixing LSP
public interface CustomerLayout {
public void render();
}
public PremiumCustomer implements CustomerLayout {
...
@Override
public void render() {
//logic ...
}
}
public FreeCustomer implements CustomerLayout{
...
@Override
public void render() {
if (!hasSeenAd)
ShowAdd();
//logic ...
}
}
public void renderView(CustomerLayout layout) {
layout.render();
}
Interface Segregation Principle
Clients should not be forced to implement interfaces they do not use.
Robert C. Martin
Violating Interface
Segregation Principle
Button valid = (Button)findViewById(R.id.valid);
valid.setOnClickListener(new View.OnClickListener {
public void onClick(View v) {
// TODO: do some stuff...
}
public void onLongClick(View v) {
// we don't need to it
}
public void onTouch(View v, MotionEvent event) {
// we don't need to it
}
});
Fixing Interface Segregation
public interface OnClickListener {
void onClick(View v);
}
public interface OnLongClickListener {
void onLongClick(View v);
}
public interface OnTouchListener {
void onTouch(View v, MotionEvent event);
}
The Dependency Inversion Principle
1. High-level modules should not depend on low-level modules. Both should
depend on abstractions.
2. Abstractions should not depend upon details. Details should depend upon
abstractions.
Robert C. Martin
Violating DIP
class Program {
public void work() {
// ....code
}
}
class Engineer{
Program program;
public void setProgram(Program p) {
program = p;
}
public void manage() {
program.work();
}
}
Fixing DIP
Interface IProgram {
public void work();
}
class Program implements IProgram{
public void work() {
// ....code
}
}
class SuperProgram implements IProgram{
public void work() {
//....code
}
}
class Engineer{
IProgram program;
public void setProgram(IProgram p) {
program = p;
}
public void manage() {
program.work();
}
}
Questions?

More Related Content

Similar to Solid principles in action

Some OOP paradigms & SOLID
Some OOP paradigms & SOLIDSome OOP paradigms & SOLID
Some OOP paradigms & SOLIDJulio Martinez
 
Class 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingClass 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingAhmed Swilam
 
Introduction to Object oriented Design
Introduction to Object oriented DesignIntroduction to Object oriented Design
Introduction to Object oriented DesignAmin Shahnazari
 
Advanced JavaScript Techniques
Advanced JavaScript TechniquesAdvanced JavaScript Techniques
Advanced JavaScript TechniquesHoat Le
 
Saindo da zona de conforto… resolvi aprender android
Saindo da zona de conforto… resolvi aprender androidSaindo da zona de conforto… resolvi aprender android
Saindo da zona de conforto… resolvi aprender androidDaniel Baccin
 
Andrei Iacob - SOLID: Strategies for Implementing Object–Oriented Design Prin...
Andrei Iacob - SOLID: Strategies for Implementing Object–Oriented Design Prin...Andrei Iacob - SOLID: Strategies for Implementing Object–Oriented Design Prin...
Andrei Iacob - SOLID: Strategies for Implementing Object–Oriented Design Prin...Constanța Developers
 
Nicola Corti - Building UI Consistent Android Apps - Codemotion Milan 2017
Nicola Corti - Building UI Consistent Android Apps - Codemotion Milan 2017Nicola Corti - Building UI Consistent Android Apps - Codemotion Milan 2017
Nicola Corti - Building UI Consistent Android Apps - Codemotion Milan 2017Codemotion
 
Clean Code - Design Patterns and Best Practices at Silicon Valley Code Camp
Clean Code - Design Patterns and Best Practices at Silicon Valley Code CampClean Code - Design Patterns and Best Practices at Silicon Valley Code Camp
Clean Code - Design Patterns and Best Practices at Silicon Valley Code CampTheo Jungeblut
 
4Developers 2015: Be pragmatic, be SOLID - Krzysztof Menżyk
4Developers 2015: Be pragmatic, be SOLID - Krzysztof Menżyk4Developers 2015: Be pragmatic, be SOLID - Krzysztof Menżyk
4Developers 2015: Be pragmatic, be SOLID - Krzysztof MenżykPROIDEA
 
Proxy & adapter pattern
Proxy & adapter patternProxy & adapter pattern
Proxy & adapter patternbabak danyal
 
Inheritance, polymorphisam, abstract classes and composition)
Inheritance, polymorphisam, abstract classes and composition)Inheritance, polymorphisam, abstract classes and composition)
Inheritance, polymorphisam, abstract classes and composition)farhan amjad
 
Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3Naga Muruga
 
Revisiting SOLID Principles
Revisiting  SOLID Principles Revisiting  SOLID Principles
Revisiting SOLID Principles Anis Ahmad
 
2009 Dotnet Information Day: More effective c#
2009 Dotnet Information Day: More effective c#2009 Dotnet Information Day: More effective c#
2009 Dotnet Information Day: More effective c#Daniel Fisher
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android InfrastructureAlexey Buzdin
 

Similar to Solid principles in action (20)

Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Some OOP paradigms & SOLID
Some OOP paradigms & SOLIDSome OOP paradigms & SOLID
Some OOP paradigms & SOLID
 
Class 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingClass 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented Programming
 
L22 Design Principles
L22 Design PrinciplesL22 Design Principles
L22 Design Principles
 
Introduction to Object oriented Design
Introduction to Object oriented DesignIntroduction to Object oriented Design
Introduction to Object oriented Design
 
Advanced JavaScript Techniques
Advanced JavaScript TechniquesAdvanced JavaScript Techniques
Advanced JavaScript Techniques
 
Saindo da zona de conforto… resolvi aprender android
Saindo da zona de conforto… resolvi aprender androidSaindo da zona de conforto… resolvi aprender android
Saindo da zona de conforto… resolvi aprender android
 
Andrei Iacob - SOLID: Strategies for Implementing Object–Oriented Design Prin...
Andrei Iacob - SOLID: Strategies for Implementing Object–Oriented Design Prin...Andrei Iacob - SOLID: Strategies for Implementing Object–Oriented Design Prin...
Andrei Iacob - SOLID: Strategies for Implementing Object–Oriented Design Prin...
 
OOP Core Concept
OOP Core ConceptOOP Core Concept
OOP Core Concept
 
Nicola Corti - Building UI Consistent Android Apps - Codemotion Milan 2017
Nicola Corti - Building UI Consistent Android Apps - Codemotion Milan 2017Nicola Corti - Building UI Consistent Android Apps - Codemotion Milan 2017
Nicola Corti - Building UI Consistent Android Apps - Codemotion Milan 2017
 
Clean Code - Design Patterns and Best Practices at Silicon Valley Code Camp
Clean Code - Design Patterns and Best Practices at Silicon Valley Code CampClean Code - Design Patterns and Best Practices at Silicon Valley Code Camp
Clean Code - Design Patterns and Best Practices at Silicon Valley Code Camp
 
4Developers 2015: Be pragmatic, be SOLID - Krzysztof Menżyk
4Developers 2015: Be pragmatic, be SOLID - Krzysztof Menżyk4Developers 2015: Be pragmatic, be SOLID - Krzysztof Menżyk
4Developers 2015: Be pragmatic, be SOLID - Krzysztof Menżyk
 
Be pragmatic, be SOLID
Be pragmatic, be SOLIDBe pragmatic, be SOLID
Be pragmatic, be SOLID
 
Proxy & adapter pattern
Proxy & adapter patternProxy & adapter pattern
Proxy & adapter pattern
 
L04 Software Design 2
L04 Software Design 2L04 Software Design 2
L04 Software Design 2
 
Inheritance, polymorphisam, abstract classes and composition)
Inheritance, polymorphisam, abstract classes and composition)Inheritance, polymorphisam, abstract classes and composition)
Inheritance, polymorphisam, abstract classes and composition)
 
Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3
 
Revisiting SOLID Principles
Revisiting  SOLID Principles Revisiting  SOLID Principles
Revisiting SOLID Principles
 
2009 Dotnet Information Day: More effective c#
2009 Dotnet Information Day: More effective c#2009 Dotnet Information Day: More effective c#
2009 Dotnet Information Day: More effective c#
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
 

Recently uploaded

Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations120cr0395
 
Glass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesGlass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesPrabhanshu Chaturvedi
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordAsst.prof M.Gokilavani
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...ranjana rawat
 
Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...Christo Ananth
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)simmis5
 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...SUHANI PANDEY
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdfankushspencer015
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptDineshKumar4165
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756dollysharma2066
 
Vivazz, Mieres Social Housing Design Spain
Vivazz, Mieres Social Housing Design SpainVivazz, Mieres Social Housing Design Spain
Vivazz, Mieres Social Housing Design Spaintimesproduction05
 
chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringmulugeta48
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTbhaskargani46
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdfKamal Acharya
 
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Bookingroncy bisnoi
 
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxfenichawla
 

Recently uploaded (20)

Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 
Glass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesGlass Ceramics: Processing and Properties
Glass Ceramics: Processing and Properties
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
 
Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)
 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
 
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
 
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
Vivazz, Mieres Social Housing Design Spain
Vivazz, Mieres Social Housing Design SpainVivazz, Mieres Social Housing Design Spain
Vivazz, Mieres Social Housing Design Spain
 
chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineering
 
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
 
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 

Solid principles in action

  • 1. SOLID Principles in Action Arash Khangaldi: @irLogcat 2018
  • 2. Agenda ● S — Single Responsibility Principle(S.R.P) ● O — Open-Closed Principle ● L — Liskov Substitution Principle ● I — Interface Segregation Principle ● D — Dependency Inversion Principle
  • 3. Single Responsibility A class should have one, and only one, reason to change. Don’t be Swiss Army Knife! In the context of the Single Responsibility Principle (SRP) we define a responsibility as “a reason for change”. If you can think of more than one motive for changing a class, then that class has more than one responsibility.
  • 5. @Override public void onBindViewHolder(ViewHolder holder, int position) { final Movie movie = movies.get(position); holder.itemView.setTag(movie); holder.title.setText(movie.getTitle()); holder.rating.setText(movie.getRating()); String genreStr = ""; for (String str: movie.getGenre()) { genreStr += str + ", "; } genreStr = genreStr.length() > 0 ? genreStr.substring(0, genreStr.length() - 2) : genreStr; holder.genre.setText(genreStr); holder.releaseYear.setText(movie.getYear()); Glide.with(holder.thumbNail.getContext()) .load(movies.get(position) .getThumbnailUrl()) .into(holder.thumbNail); }
  • 7. @Override public void onBindViewHolder(ViewHolder holder, int position) { final Movie movie = movies.get(position); holder.itemView.setTag(movie); holder.title.setText(movie.getTitle()); holder.rating.setText(movie.getRating()); holder.genre.setText( ArraysUtil.convertArrayListToString(movie.getGenre())); holder.releaseYear.setText(movie.getYear()); Glide.with(holder.thumbNail.getContext()) .load(movies.get(position) .getThumbnailUrl()) .into(holder.thumbNail); }
  • 9. @Test public void testScenario1And2() { //... assertEqual(resultOne, mUnderTest.getScenarioOne()); assertEqual(resultTwo, mUnderTest.getScenarioTwo()); }
  • 11. @Test public void testScenarioOne() { //... assertEqual(resultOne, mUnderTest.getScenarioOne()); } @Test public void testScenarioTwo() { //... assertEqual(resultTwo, mUnderTest.getScenarioTwo()); }
  • 12. Open/Closed Principle You should be able to extend a classes behavior, without modifying it. This principle is the foundation for building code that is maintainable and reusable. Robert C. Martin
  • 14. public class Music { private String title; private String uri; // getters/setters ... } public class DataFactory { public ArrayList<String> fetchUri(ArrayList<Object>... medias) { ArrayList<String> uris = new ArrayList<String>(); for (Object media : medias) { if (media instanceof Music) { Music music = (Music)media; uris.add(Music.getUri()); } else if (media instanceof Image) { Image image = (Image)media; uris.add( Environment.getStorageDirectory()+ image.getPath()); } else { throw new RuntimeException("Media not supported"); } } return uris; } } public class Image { private String title; private String user; private String path; // getters/setters ... }
  • 16. public interface Media { String getPath(); } public class Music implements Media{ private String title; private String uri; // getters/setters ... @Override public getPath() { return //...; } } // Image.java public class Image implements Media{ private String title; // getters/setters ... @Override public getPath() { return //...; } }
  • 17. public class DataFactory { public ArrayList<String> fetchUri(ArrayList<Media>... medias) { ArrayList<String> uris = new ArrayList<String>(); for (Media media : medias) { uris.add(shape.getArea()); } return area; } }
  • 18. The Liskov Substitution Principle (LSP) Child classes should never break the parent class’ type definitions.
  • 19.
  • 21. public interface CustomerLayout { public void render(); } public PremiumCustomer implements CustomerLayout { ... @Override public void render() { //logic ... } } public FreeCustomer implements CustomerLayout{ ... @Override public void render() { if (!hasSeenAd) return; //logic ... } } public void renderView(CustomerLayout layout) { layout.render(); }
  • 23. public interface CustomerLayout { public void render(); } public PremiumCustomer implements CustomerLayout { ... @Override public void render() { //logic ... } } public FreeCustomer implements CustomerLayout{ ... @Override public void render() { if (!hasSeenAd) ShowAdd(); //logic ... } } public void renderView(CustomerLayout layout) { layout.render(); }
  • 24. Interface Segregation Principle Clients should not be forced to implement interfaces they do not use. Robert C. Martin
  • 25.
  • 27. Button valid = (Button)findViewById(R.id.valid); valid.setOnClickListener(new View.OnClickListener { public void onClick(View v) { // TODO: do some stuff... } public void onLongClick(View v) { // we don't need to it } public void onTouch(View v, MotionEvent event) { // we don't need to it } });
  • 29. public interface OnClickListener { void onClick(View v); } public interface OnLongClickListener { void onLongClick(View v); } public interface OnTouchListener { void onTouch(View v, MotionEvent event); }
  • 30. The Dependency Inversion Principle 1. High-level modules should not depend on low-level modules. Both should depend on abstractions. 2. Abstractions should not depend upon details. Details should depend upon abstractions. Robert C. Martin
  • 31.
  • 33. class Program { public void work() { // ....code } } class Engineer{ Program program; public void setProgram(Program p) { program = p; } public void manage() { program.work(); } }
  • 35. Interface IProgram { public void work(); } class Program implements IProgram{ public void work() { // ....code } } class SuperProgram implements IProgram{ public void work() { //....code } } class Engineer{ IProgram program; public void setProgram(IProgram p) { program = p; } public void manage() { program.work(); } }