The Single Responsibility Principle
Lars-Erik Kindblad
Senior Consultant
Blog: kindblad.com
Agenda
What is the Single Responsibility Principle?
Code Sample
Summary
Single Responsibility Principle
Single Responsibility Principle = SRP
1 of the 5 SOLID principles for creating better object-oriented code
 The Single Responsibility Principle
 The Open Closed Principle
 The Liskov Substitution Principle
 The Interface Segregation Principle
 The Dependency Inversion Principle
SRP states that ”a class or module should have one, and only one, reason
to change”
 A class should do one thing
 A class should have only one responsibility
The benefit: smaller classes that are easier to read, maintain and unit-test
The God Object
A God object is an object that knows too much or does too much
The opposite of the SRP
Single Responsibility Objects
CODE SAMPLE
Database code
Send mail code
1. Extract mail sending code
2. Extract database code
Repositories are potential God-objects
3. Replace Repository.GetUser with a DbCommand
4. Replace Repository.AddUser with a DbCommand
5. Replace Repository.DeleteUser with a DbCommand
UserManager looks like
a facade class
... Extract
6. Extract RegisterUser
7. Rename UserManager
... to UserFacade
Not every dependency
are needed at all times
8. Change to a Service Locator
9. Validation
Could be extracted but not
needed now since the class
is small...
Overview
AddUserDbCommand
DeleteUserDbCommand
GetUserDbCommand
SendEmailConfirmationRegisterUser
UserFacade
Remove?
Summary
A class following the single responsibility principle is a class that does only
one thing and has only one reason to change
The opposite of SRP is a God-object
Benefits
 Easy to give the class a good name
 Less code per class means reduced complexity, less errors, easier to maintain, extend
and test
Arguments against
 Too many classes
 Difficult to understand the big picture
The pros outweights the cons – SRP is a requirement for
writing maintainable unit-tests
QUESTIONS?
The information contained in this presentation is proprietary.
© 2012 Capgemini. All rights reserved.
www.capgemini.com
About Capgemini
With more than 120,000 people in 40 countries, Capgemini is one
of the world's foremost providers of consulting, technology and
outsourcing services. The Group reported 2011 global revenues
of EUR 9.7 billion.
Together with its clients, Capgemini creates and delivers
business and technology solutions that fit their needs and drive
the results they want. A deeply multicultural organization,
Capgemini has developed its own way of working, the
Collaborative Business ExperienceTM, and draws on Rightshore ®,
its worldwide delivery model.
Rightshore® is a trademark belonging to Capgemini

The Single Responsibility Principle