SlideShare a Scribd company logo
1 of 43
Download to read offline
Single Responsibility Principle
Do One thing! Do It Well!
SOLID
Five basic principles of object-oriented programming and
design that deals with “dependency management”
● S SRP Single responsibility principle
● O OCP Open/closed principle
● L LSP Liskov substitution principle
● I ISP Interface segregation principle
● D DIP Dependency inversion principle
Principles vs. Patterns
A pattern in “is a general reusable solution to a
commonly occurring problem within a given context in
software design”
● Use a pattern to solve a known problem.
● Use the principles to identify the problem and come up
with the solution.
Single Responsibility Principle
“A class should have one and only one reason to change,
meaning that a class should have only one job.”
Not responsible for bug fixes or refactoring. Those things
are the responsibility of the programmer, not of the
program
Then what’s a program responsible to?
First Example
class Employee {
public Money calculatePay()
public void save()
public String reportHours()
}
Three reasons to change:
● The business rules having to do with calculating pay.
● The database schema.
● The format of the hours report.
Step by Step Example
New request has arrived:
1. Generate a weekly report of online users
2. Send it to Jill in France
First glance ...
1- Monthly instead of weekly
3- Jill gets fired
2- Change
report’s format
to CSV
Possible Reasons to Change
1- Get a list of users upon a criteria
2- Format the message
3- Deliver the report
Break down:
Responsibilities
handled in each
method in one
class
4- Put it all togather
1- CSV Formatter
2- Query execution
Break down:
Separate
among many
classes
3- Report generation
Inject these two, so
UserWeeklyReport would rarely
change
4- Mail delivery
And finally ….
5- Parse users
Sketch - Relations
ReportMailer UserWeeklyReport
ReportDataCSVCompiler UserWeeklyReportData
User
Formatting
Parsing users
Getting users
Mail
delivery
Report generation
Separation of Concerns
Classes are not the end. Applicable on every level!
It goes back even to the days when Structured
Programming was all the hype
Applicable on functions, classes, modules, …
Separation of Concerns
● OOP languages separate concerns into objects
● Architectural design patterns like MVC separate
content from presentation and the data-processing
(model) from content
● Service-oriented design use services
● Procedural languages such as C use functions.
Method-wise Example
● In a class that handles syncing local data with Dropbox
● Show up an alert view to handle some clashes
● Due to some design limitation, the following method
gets called to handle the user’s choice for each alert
-alertView:(UIAlertView *)alertView
clickedButtonAtIndex:(NSInteger)buttonIndex
Scary to look !
Response to “Notepad clashes”
alert
Three
sub
cases!
Response to “older DB”
alert
Handle project clashes
Logical separation
The purpose of this method is clear:
“switching”
Each of the other three methods handle
one case
1
2
3
We can apply the same
here
1
2
3
Examples of “Frequent” Responsibilities
● Persistence to storage
● Validation
● Notification
● Error Handling
● Logging
● Class Selection / Instantiation
● Formatting
● Parsing
● Mapping
How do you know that SRP is violated?
First answer: “Length”
Popular choices:
Classes shouldn’t exceed 200 lines of code (exclude
comments)
Methods shouldn’t exceed 30 lines of code
Is this a solid metric? … Not exactly!
Less than 200
lines of code
Does it follow SRP
correctly?
Less than 200
lines of code
Does it follow SRP
correctly?
Code to “prepare”
for requests
performed for
Dashboard
Descriptors.
Similar to routing
Mapping
JSON <-> Objects
Various requests
performed on
Dashboard
Reasons “Mapping” part would change
● Web request refactored
● Dashboard needed to be used in
another request with different
parameters
Encapsulate a single request into a proxy object
Few reasons to make this class change
Biggest benefit: Dashboard is simpler and shorter
Length ??
So length isn’t a very accurate metric.
If a class is higher than 200 loc, then it’s problem!
If it’s fewer than 200 loc, that doesn’t mean you’re clear!
SRP Violation Smells
● Class has too many instance variables and methods
○ Especially, when you always use a group of them together
● The test class becomes too complicated
○ Too many mock objects
○ Too many test cases
● Use “and” or “or” in names
● Class with low cohesion
○ Many parts not related to each other
● Class / Method is Long
SRP Violation Smells
● Change In One Place Breaks Another
● Shotgun Effect
● Unable to Encapsulate a Module
● Class has too many dependencies
Why?
● Organize the code
○ So you know where to look for the next request
● Code Changes
○ If you have to refactor one class, only one class will change
● Less fragile
○ “You were only supposed to send an email, how did you end
up deleting all the data?”
Why?
● Testability
○ Less test cases for a class with one job to do
● Code sharing
○ All previous reasons are equally or more important than this
one!
○ Don’t wait till you have to reuse the code, start breaking
down your code when it makes sense.
Complex view example
A controller that populates a table view and a charts
area with data retrieved from another object
Edit and
filter data
Already
separated
Summary
data in a
table
Charts
Data source to
ChartsEngine: Provides
needed content to the
object that draws the
charts
~ 50 lines
Source to the
side table view
~ 40 lines
Another responsibility: Provide a
widget builder so other object can
use it build it.
Get data and show it in
view
Separate providing data to
table in a new object
And one for charts
Add a couple of
lines to initialize
those helpers
and provide
data to them
And the view controller
drops to ~ 100 lines of
total code
One clear responsibility:
Get data from a data
loader object and
provide to “view source”
object
We didn’t handle
that yet! But you get
the picture...
Correlation with Frameworks
Sometimes, the way the framework is designed makes it
easy to put all your code in one place
● iOS: View controllers and application delegates
● Android: Activities
● RoR: ActiveRecord models
Monster AppDelegate - Example Responsibilities
● Receive application’s notifications
● Register for a 3rd party service
● Handle global view settings
● Show notification for version updates and handle
user’s action
● Dropbox connection
● Handle push notifications
Example Patterns to Decompose Fat Classes
● Standard composition / Delegation
○ Two basic design patterns
○ Break a complex class into smaller ones
● View objects / View model / Presenter
○ If some logic is needed to prepare the model for view
● Decorator
○ Put the extra behaviour in a new class
● Specific patterns to specific problems
○ e.g. Factory / Builder for object creation
References
1. The Principles of OOD (Uncle Bob)
2. SOLID (Wikipedia)
3. Software Design Pattern (Wikipedia)
4. Uncle Bob (blog.8thlight.com)
5. Ruby Example (John Bohn)
6. Separation of Concerns (Wikipedia)
7. Examples of Responsiblities (deviq.com)
8. Why SRP and SRP Smells (Java Code Geeks)
9. Fat ActiveRecord Models (blog.codeclimate.com)
10. Active Record Breaks SRP by Design (sitepoint.com)
11. Active Record Breaks SRP by Design (programmers.stackexchange)
12. Patterns to Destroy Big View Controllers (Soroush Khanlou)

More Related Content

What's hot

Solid principles
Solid principlesSolid principles
Solid principlesToan Nguyen
 
Learning solid principles using c#
Learning solid principles using c#Learning solid principles using c#
Learning solid principles using c#Aditya Kumar Rajan
 
Geecon09: SOLID Design Principles
Geecon09: SOLID Design PrinciplesGeecon09: SOLID Design Principles
Geecon09: SOLID Design PrinciplesBruno Bossola
 
Introduction to MongoDB.pptx
Introduction to MongoDB.pptxIntroduction to MongoDB.pptx
Introduction to MongoDB.pptxSurya937648
 
SOLID Design Principles applied in Java
SOLID Design Principles applied in JavaSOLID Design Principles applied in Java
SOLID Design Principles applied in JavaIonut Bilica
 
Design principles - SOLID
Design principles - SOLIDDesign principles - SOLID
Design principles - SOLIDPranalee Rokde
 
SOLID Design Principles
SOLID Design PrinciplesSOLID Design Principles
SOLID Design PrinciplesSamuel Breed
 
Design Pattern - Những công thức vàng trong thiết kế
Design Pattern - Những công thức vàng trong thiết kếDesign Pattern - Những công thức vàng trong thiết kế
Design Pattern - Những công thức vàng trong thiết kếNhật Nguyễn Khắc
 
SOLID - Những nguyên lí sống còn
SOLID - Những nguyên lí sống cònSOLID - Những nguyên lí sống còn
SOLID - Những nguyên lí sống cònNhật Nguyễn Khắc
 
Solid design principles
Solid design principlesSolid design principles
Solid design principlesMahmoud Asadi
 
Modern UI Development With Node.js
Modern UI Development With Node.jsModern UI Development With Node.js
Modern UI Development With Node.jsRyan Anklam
 
Clean Architecture
Clean ArchitectureClean Architecture
Clean ArchitectureBadoo
 
Introducing Clean Architecture
Introducing Clean ArchitectureIntroducing Clean Architecture
Introducing Clean ArchitectureRoc Boronat
 

What's hot (20)

Solid principles
Solid principlesSolid principles
Solid principles
 
Learning solid principles using c#
Learning solid principles using c#Learning solid principles using c#
Learning solid principles using c#
 
Geecon09: SOLID Design Principles
Geecon09: SOLID Design PrinciplesGeecon09: SOLID Design Principles
Geecon09: SOLID Design Principles
 
Introduction to MongoDB.pptx
Introduction to MongoDB.pptxIntroduction to MongoDB.pptx
Introduction to MongoDB.pptx
 
SOLID Design Principles applied in Java
SOLID Design Principles applied in JavaSOLID Design Principles applied in Java
SOLID Design Principles applied in Java
 
Princípios S.O.L.I.D.
Princípios S.O.L.I.D.Princípios S.O.L.I.D.
Princípios S.O.L.I.D.
 
Design principles - SOLID
Design principles - SOLIDDesign principles - SOLID
Design principles - SOLID
 
SOLID Design Principles
SOLID Design PrinciplesSOLID Design Principles
SOLID Design Principles
 
Design Pattern - Những công thức vàng trong thiết kế
Design Pattern - Những công thức vàng trong thiết kếDesign Pattern - Những công thức vàng trong thiết kế
Design Pattern - Những công thức vàng trong thiết kế
 
SOLID - Những nguyên lí sống còn
SOLID - Những nguyên lí sống cònSOLID - Những nguyên lí sống còn
SOLID - Những nguyên lí sống còn
 
SOLID Principles
SOLID PrinciplesSOLID Principles
SOLID Principles
 
Solid principles
Solid principlesSolid principles
Solid principles
 
Solid design principles
Solid design principlesSolid design principles
Solid design principles
 
Modern UI Development With Node.js
Modern UI Development With Node.jsModern UI Development With Node.js
Modern UI Development With Node.js
 
Software Architecture - Quiz Questions
Software Architecture - Quiz QuestionsSoftware Architecture - Quiz Questions
Software Architecture - Quiz Questions
 
Solid Principles
Solid PrinciplesSolid Principles
Solid Principles
 
Clean Architecture
Clean ArchitectureClean Architecture
Clean Architecture
 
Introducing Clean Architecture
Introducing Clean ArchitectureIntroducing Clean Architecture
Introducing Clean Architecture
 
Princípios SOLID
Princípios SOLIDPrincípios SOLID
Princípios SOLID
 
Solid Principle
Solid PrincipleSolid Principle
Solid Principle
 

Similar to Single Responsibility Principle

Software Design Principles and Best Practices - Satyajit Dey
Software Design Principles and Best Practices - Satyajit DeySoftware Design Principles and Best Practices - Satyajit Dey
Software Design Principles and Best Practices - Satyajit DeyCefalo
 
Software Craftmanship - Cours Polytech
Software Craftmanship - Cours PolytechSoftware Craftmanship - Cours Polytech
Software Craftmanship - Cours Polytechyannick grenzinger
 
Object Oriented, Design patterns and data modelling worshop
Object Oriented, Design patterns and data modelling worshopObject Oriented, Design patterns and data modelling worshop
Object Oriented, Design patterns and data modelling worshopMohammad Shawahneh
 
Boston Startup School - OO Design
Boston Startup School - OO DesignBoston Startup School - OO Design
Boston Startup School - OO DesignBryan Warner
 
Object Oriented Concepts and Principles
Object Oriented Concepts and PrinciplesObject Oriented Concepts and Principles
Object Oriented Concepts and Principlesdeonpmeyer
 
GoF Design patterns I: Introduction + Structural Patterns
GoF Design patterns I:   Introduction + Structural PatternsGoF Design patterns I:   Introduction + Structural Patterns
GoF Design patterns I: Introduction + Structural PatternsSameh Deabes
 
1. oop with c++ get 410 day 1
1. oop with c++ get 410   day 11. oop with c++ get 410   day 1
1. oop with c++ get 410 day 1Mukul kumar Neal
 
From Good to SOLID: How to become a better PHP developer
From Good to SOLID: How to become a better PHP developerFrom Good to SOLID: How to become a better PHP developer
From Good to SOLID: How to become a better PHP developerKaterina Trajchevska
 
Clean Code - Part 2
Clean Code - Part 2Clean Code - Part 2
Clean Code - Part 2Knoldus Inc.
 
UNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxUNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxanguraju1
 
Design poo my_jug_en_ppt
Design poo my_jug_en_pptDesign poo my_jug_en_ppt
Design poo my_jug_en_pptagnes_crepet
 
Software design principles - jinal desai
Software design principles - jinal desaiSoftware design principles - jinal desai
Software design principles - jinal desaijinaldesailive
 
1. OBJECT ORIENTED PROGRAMMING USING JAVA - OOps Concepts.ppt
1. OBJECT ORIENTED PROGRAMMING USING JAVA - OOps Concepts.ppt1. OBJECT ORIENTED PROGRAMMING USING JAVA - OOps Concepts.ppt
1. OBJECT ORIENTED PROGRAMMING USING JAVA - OOps Concepts.pptsagarjsicg
 
Code Smells and Refactoring - Satyajit Dey & Ashif Iqbal
Code Smells and Refactoring - Satyajit Dey & Ashif IqbalCode Smells and Refactoring - Satyajit Dey & Ashif Iqbal
Code Smells and Refactoring - Satyajit Dey & Ashif IqbalCefalo
 
Introduction to object oriented language
Introduction to object oriented languageIntroduction to object oriented language
Introduction to object oriented languagefarhan amjad
 

Similar to Single Responsibility Principle (20)

Software Design Principles and Best Practices - Satyajit Dey
Software Design Principles and Best Practices - Satyajit DeySoftware Design Principles and Best Practices - Satyajit Dey
Software Design Principles and Best Practices - Satyajit Dey
 
Software Craftmanship - Cours Polytech
Software Craftmanship - Cours PolytechSoftware Craftmanship - Cours Polytech
Software Craftmanship - Cours Polytech
 
Object Oriented, Design patterns and data modelling worshop
Object Oriented, Design patterns and data modelling worshopObject Oriented, Design patterns and data modelling worshop
Object Oriented, Design patterns and data modelling worshop
 
Boston Startup School - OO Design
Boston Startup School - OO DesignBoston Startup School - OO Design
Boston Startup School - OO Design
 
Object Oriented Concepts and Principles
Object Oriented Concepts and PrinciplesObject Oriented Concepts and Principles
Object Oriented Concepts and Principles
 
GoF Design patterns I: Introduction + Structural Patterns
GoF Design patterns I:   Introduction + Structural PatternsGoF Design patterns I:   Introduction + Structural Patterns
GoF Design patterns I: Introduction + Structural Patterns
 
OO Design Principles
OO Design PrinciplesOO Design Principles
OO Design Principles
 
L05 Design Patterns
L05 Design PatternsL05 Design Patterns
L05 Design Patterns
 
1. oop with c++ get 410 day 1
1. oop with c++ get 410   day 11. oop with c++ get 410   day 1
1. oop with c++ get 410 day 1
 
From Good to SOLID: How to become a better PHP developer
From Good to SOLID: How to become a better PHP developerFrom Good to SOLID: How to become a better PHP developer
From Good to SOLID: How to become a better PHP developer
 
Clean Code - Part 2
Clean Code - Part 2Clean Code - Part 2
Clean Code - Part 2
 
UNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxUNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptx
 
Design poo my_jug_en_ppt
Design poo my_jug_en_pptDesign poo my_jug_en_ppt
Design poo my_jug_en_ppt
 
Software design principles - jinal desai
Software design principles - jinal desaiSoftware design principles - jinal desai
Software design principles - jinal desai
 
L03 Design Patterns
L03 Design PatternsL03 Design Patterns
L03 Design Patterns
 
1. OBJECT ORIENTED PROGRAMMING USING JAVA - OOps Concepts.ppt
1. OBJECT ORIENTED PROGRAMMING USING JAVA - OOps Concepts.ppt1. OBJECT ORIENTED PROGRAMMING USING JAVA - OOps Concepts.ppt
1. OBJECT ORIENTED PROGRAMMING USING JAVA - OOps Concepts.ppt
 
Code Smells and Refactoring - Satyajit Dey & Ashif Iqbal
Code Smells and Refactoring - Satyajit Dey & Ashif IqbalCode Smells and Refactoring - Satyajit Dey & Ashif Iqbal
Code Smells and Refactoring - Satyajit Dey & Ashif Iqbal
 
Intro to ember.js
Intro to ember.jsIntro to ember.js
Intro to ember.js
 
Software development fundamentals
Software development fundamentalsSoftware development fundamentals
Software development fundamentals
 
Introduction to object oriented language
Introduction to object oriented languageIntroduction to object oriented language
Introduction to object oriented language
 

More from BADR

Sunspot - The Ruby Way into Solr
Sunspot - The Ruby Way into SolrSunspot - The Ruby Way into Solr
Sunspot - The Ruby Way into SolrBADR
 
Docker up and Running For Web Developers
Docker up and Running For Web DevelopersDocker up and Running For Web Developers
Docker up and Running For Web DevelopersBADR
 
Vue.js
Vue.jsVue.js
Vue.jsBADR
 
There and Back Again - A Tale of Programming Languages
There and Back Again - A Tale of Programming LanguagesThere and Back Again - A Tale of Programming Languages
There and Back Again - A Tale of Programming LanguagesBADR
 
Take Pride in Your Code - Test-Driven Development
Take Pride in Your Code - Test-Driven DevelopmentTake Pride in Your Code - Test-Driven Development
Take Pride in Your Code - Test-Driven DevelopmentBADR
 
NoSQL Databases
NoSQL DatabasesNoSQL Databases
NoSQL DatabasesBADR
 
Explicit Semantic Analysis
Explicit Semantic AnalysisExplicit Semantic Analysis
Explicit Semantic AnalysisBADR
 
Getting some Git
Getting some GitGetting some Git
Getting some GitBADR
 
ReactiveX
ReactiveXReactiveX
ReactiveXBADR
 
Algorithms - A Sneak Peek
Algorithms - A Sneak PeekAlgorithms - A Sneak Peek
Algorithms - A Sneak PeekBADR
 
Android from A to Z
Android from A to ZAndroid from A to Z
Android from A to ZBADR
 
Apache Hadoop - Big Data Engineering
Apache Hadoop - Big Data EngineeringApache Hadoop - Big Data Engineering
Apache Hadoop - Big Data EngineeringBADR
 
MySQL Indexing
MySQL IndexingMySQL Indexing
MySQL IndexingBADR
 
Duckville - The Strategy Design Pattern
Duckville - The Strategy Design PatternDuckville - The Strategy Design Pattern
Duckville - The Strategy Design PatternBADR
 
The Perks and Perils of the Singleton Design Pattern
The Perks and Perils of the Singleton Design PatternThe Perks and Perils of the Singleton Design Pattern
The Perks and Perils of the Singleton Design PatternBADR
 

More from BADR (15)

Sunspot - The Ruby Way into Solr
Sunspot - The Ruby Way into SolrSunspot - The Ruby Way into Solr
Sunspot - The Ruby Way into Solr
 
Docker up and Running For Web Developers
Docker up and Running For Web DevelopersDocker up and Running For Web Developers
Docker up and Running For Web Developers
 
Vue.js
Vue.jsVue.js
Vue.js
 
There and Back Again - A Tale of Programming Languages
There and Back Again - A Tale of Programming LanguagesThere and Back Again - A Tale of Programming Languages
There and Back Again - A Tale of Programming Languages
 
Take Pride in Your Code - Test-Driven Development
Take Pride in Your Code - Test-Driven DevelopmentTake Pride in Your Code - Test-Driven Development
Take Pride in Your Code - Test-Driven Development
 
NoSQL Databases
NoSQL DatabasesNoSQL Databases
NoSQL Databases
 
Explicit Semantic Analysis
Explicit Semantic AnalysisExplicit Semantic Analysis
Explicit Semantic Analysis
 
Getting some Git
Getting some GitGetting some Git
Getting some Git
 
ReactiveX
ReactiveXReactiveX
ReactiveX
 
Algorithms - A Sneak Peek
Algorithms - A Sneak PeekAlgorithms - A Sneak Peek
Algorithms - A Sneak Peek
 
Android from A to Z
Android from A to ZAndroid from A to Z
Android from A to Z
 
Apache Hadoop - Big Data Engineering
Apache Hadoop - Big Data EngineeringApache Hadoop - Big Data Engineering
Apache Hadoop - Big Data Engineering
 
MySQL Indexing
MySQL IndexingMySQL Indexing
MySQL Indexing
 
Duckville - The Strategy Design Pattern
Duckville - The Strategy Design PatternDuckville - The Strategy Design Pattern
Duckville - The Strategy Design Pattern
 
The Perks and Perils of the Singleton Design Pattern
The Perks and Perils of the Singleton Design PatternThe Perks and Perils of the Singleton Design Pattern
The Perks and Perils of the Singleton Design Pattern
 

Recently uploaded

The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 

Recently uploaded (20)

The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 

Single Responsibility Principle

  • 1.
  • 2. Single Responsibility Principle Do One thing! Do It Well!
  • 3. SOLID Five basic principles of object-oriented programming and design that deals with “dependency management” ● S SRP Single responsibility principle ● O OCP Open/closed principle ● L LSP Liskov substitution principle ● I ISP Interface segregation principle ● D DIP Dependency inversion principle
  • 4. Principles vs. Patterns A pattern in “is a general reusable solution to a commonly occurring problem within a given context in software design” ● Use a pattern to solve a known problem. ● Use the principles to identify the problem and come up with the solution.
  • 5. Single Responsibility Principle “A class should have one and only one reason to change, meaning that a class should have only one job.” Not responsible for bug fixes or refactoring. Those things are the responsibility of the programmer, not of the program Then what’s a program responsible to?
  • 6. First Example class Employee { public Money calculatePay() public void save() public String reportHours() } Three reasons to change: ● The business rules having to do with calculating pay. ● The database schema. ● The format of the hours report.
  • 7. Step by Step Example New request has arrived: 1. Generate a weekly report of online users 2. Send it to Jill in France
  • 9. 1- Monthly instead of weekly 3- Jill gets fired 2- Change report’s format to CSV Possible Reasons to Change
  • 10. 1- Get a list of users upon a criteria 2- Format the message 3- Deliver the report Break down: Responsibilities handled in each method in one class 4- Put it all togather
  • 11. 1- CSV Formatter 2- Query execution Break down: Separate among many classes
  • 12. 3- Report generation Inject these two, so UserWeeklyReport would rarely change 4- Mail delivery
  • 13. And finally …. 5- Parse users
  • 14. Sketch - Relations ReportMailer UserWeeklyReport ReportDataCSVCompiler UserWeeklyReportData User Formatting Parsing users Getting users Mail delivery Report generation
  • 15. Separation of Concerns Classes are not the end. Applicable on every level! It goes back even to the days when Structured Programming was all the hype Applicable on functions, classes, modules, …
  • 16. Separation of Concerns ● OOP languages separate concerns into objects ● Architectural design patterns like MVC separate content from presentation and the data-processing (model) from content ● Service-oriented design use services ● Procedural languages such as C use functions.
  • 17. Method-wise Example ● In a class that handles syncing local data with Dropbox ● Show up an alert view to handle some clashes ● Due to some design limitation, the following method gets called to handle the user’s choice for each alert -alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
  • 19. Response to “Notepad clashes” alert Three sub cases! Response to “older DB” alert Handle project clashes
  • 20. Logical separation The purpose of this method is clear: “switching” Each of the other three methods handle one case 1 2 3 We can apply the same here 1 2 3
  • 21. Examples of “Frequent” Responsibilities ● Persistence to storage ● Validation ● Notification ● Error Handling ● Logging ● Class Selection / Instantiation ● Formatting ● Parsing ● Mapping
  • 22. How do you know that SRP is violated? First answer: “Length” Popular choices: Classes shouldn’t exceed 200 lines of code (exclude comments) Methods shouldn’t exceed 30 lines of code Is this a solid metric? … Not exactly!
  • 23. Less than 200 lines of code Does it follow SRP correctly?
  • 24. Less than 200 lines of code Does it follow SRP correctly? Code to “prepare” for requests performed for Dashboard Descriptors. Similar to routing Mapping JSON <-> Objects Various requests performed on Dashboard
  • 25. Reasons “Mapping” part would change ● Web request refactored ● Dashboard needed to be used in another request with different parameters
  • 26. Encapsulate a single request into a proxy object Few reasons to make this class change Biggest benefit: Dashboard is simpler and shorter
  • 27. Length ?? So length isn’t a very accurate metric. If a class is higher than 200 loc, then it’s problem! If it’s fewer than 200 loc, that doesn’t mean you’re clear!
  • 28. SRP Violation Smells ● Class has too many instance variables and methods ○ Especially, when you always use a group of them together ● The test class becomes too complicated ○ Too many mock objects ○ Too many test cases ● Use “and” or “or” in names ● Class with low cohesion ○ Many parts not related to each other ● Class / Method is Long
  • 29. SRP Violation Smells ● Change In One Place Breaks Another ● Shotgun Effect ● Unable to Encapsulate a Module ● Class has too many dependencies
  • 30. Why? ● Organize the code ○ So you know where to look for the next request ● Code Changes ○ If you have to refactor one class, only one class will change ● Less fragile ○ “You were only supposed to send an email, how did you end up deleting all the data?”
  • 31. Why? ● Testability ○ Less test cases for a class with one job to do ● Code sharing ○ All previous reasons are equally or more important than this one! ○ Don’t wait till you have to reuse the code, start breaking down your code when it makes sense.
  • 32. Complex view example A controller that populates a table view and a charts area with data retrieved from another object
  • 33.
  • 34.
  • 36. Data source to ChartsEngine: Provides needed content to the object that draws the charts ~ 50 lines Source to the side table view ~ 40 lines Another responsibility: Provide a widget builder so other object can use it build it. Get data and show it in view
  • 37. Separate providing data to table in a new object
  • 38. And one for charts
  • 39. Add a couple of lines to initialize those helpers and provide data to them And the view controller drops to ~ 100 lines of total code One clear responsibility: Get data from a data loader object and provide to “view source” object We didn’t handle that yet! But you get the picture...
  • 40. Correlation with Frameworks Sometimes, the way the framework is designed makes it easy to put all your code in one place ● iOS: View controllers and application delegates ● Android: Activities ● RoR: ActiveRecord models
  • 41. Monster AppDelegate - Example Responsibilities ● Receive application’s notifications ● Register for a 3rd party service ● Handle global view settings ● Show notification for version updates and handle user’s action ● Dropbox connection ● Handle push notifications
  • 42. Example Patterns to Decompose Fat Classes ● Standard composition / Delegation ○ Two basic design patterns ○ Break a complex class into smaller ones ● View objects / View model / Presenter ○ If some logic is needed to prepare the model for view ● Decorator ○ Put the extra behaviour in a new class ● Specific patterns to specific problems ○ e.g. Factory / Builder for object creation
  • 43. References 1. The Principles of OOD (Uncle Bob) 2. SOLID (Wikipedia) 3. Software Design Pattern (Wikipedia) 4. Uncle Bob (blog.8thlight.com) 5. Ruby Example (John Bohn) 6. Separation of Concerns (Wikipedia) 7. Examples of Responsiblities (deviq.com) 8. Why SRP and SRP Smells (Java Code Geeks) 9. Fat ActiveRecord Models (blog.codeclimate.com) 10. Active Record Breaks SRP by Design (sitepoint.com) 11. Active Record Breaks SRP by Design (programmers.stackexchange) 12. Patterns to Destroy Big View Controllers (Soroush Khanlou)